from __future__ import annotations

import csv
import json
from pathlib import Path

from email_enrichment.config import ProfileConfig
from email_enrichment.linkedin_merge import merge_into_csv

FIXTURE = Path(__file__).resolve().parent / "fixtures" / "advmfr_sample.csv"
PROFILES_DIR = Path(__file__).resolve().parents[1] / "profiles"


def test_merge_appends_pattern_seed_with_email(tmp_path: Path) -> None:
    """
    LinkedIn's real job here: reveal an already-known contact's email so the
    domain pattern can be learned. The merged CSV MUST contain the revealed
    email in the Email column.
    """
    cfg = ProfileConfig.load(PROFILES_DIR / "advmfr.yml")
    jsonl_path = tmp_path / "linkedin.jsonl"
    jsonl_path.write_text(
        json.dumps(
            {
                "company": "Sonara Jewelry",
                "domain": "sonarajewelry.com",
                "contacts": [
                    {
                        "full_name": "Maria Lopez",
                        "email": "m.lopez@sonarajewelry.com",
                        "title": "Head of Wholesale",
                        "linkedin_url": "https://li/x",
                    },
                ],
            }
        )
        + "\n",
        encoding="utf-8",
    )
    output = tmp_path / "merged.csv"
    appended = merge_into_csv(FIXTURE, jsonl_path, output, cfg)
    assert appended == 1

    with output.open(encoding="utf-8", newline="") as f:
        rows = list(csv.DictReader(f))
    seed_row = next(r for r in rows if r["Contact Name"] == "Maria Lopez")
    assert seed_row["Email"] == "m.lopez@sonarajewelry.com"
    assert seed_row["Company/Brand Name"] == "Sonara Jewelry"


def test_merge_accepts_contacts_without_email(tmp_path: Path) -> None:
    cfg = ProfileConfig.load(PROFILES_DIR / "advmfr.yml")
    jsonl_path = tmp_path / "linkedin.jsonl"
    jsonl_path.write_text(
        json.dumps(
            {
                "company": "Dasan",
                "contacts": [{"full_name": "Sarah Lee", "title": "CEO"}],
            }
        )
        + "\n",
        encoding="utf-8",
    )
    output = tmp_path / "merged.csv"
    appended = merge_into_csv(FIXTURE, jsonl_path, output, cfg)
    assert appended == 1
    with output.open(encoding="utf-8", newline="") as f:
        rows = list(csv.DictReader(f))
    seed_row = next(r for r in rows if r["Contact Name"] == "Sarah Lee")
    assert seed_row["Email"] == ""
