from __future__ import annotations

from pathlib import Path

import httpx
import pytest

from email_enrichment.config import ProfileConfig
from email_enrichment.enricher import run_pass_one
from email_enrichment.reacher import ReacherClient

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


def _reacher_with(handler) -> ReacherClient:
    client = ReacherClient(secret="dummy")
    client._client.close()
    client._client = httpx.Client(
        transport=httpx.MockTransport(handler), headers=client._headers, timeout=5.0
    )
    return client


def test_run_pass_one_writes_outputs(tmp_path: Path) -> None:
    cfg = ProfileConfig.load(PROFILES_DIR / "advmfr.yml")

    def handler(request: httpx.Request) -> httpx.Response:
        body = request.read().decode("utf-8")
        # Declare every known email "safe"; everything else "unknown".
        known = {"jmitchell@dasaninc.com", "sales@sonarajewelry.com",
                 "majed@mejuri.com", "noura@mejuri.com", "nicole@mejuri.com",
                 "d'arcy@heyrowan.com", "hillary@shr8.com"}
        verdict = "safe" if any(e in body.lower() for e in known) else "unknown"
        return httpx.Response(
            200,
            json={
                "input": "x",
                "is_reachable": verdict,
                "smtp": {"is_catch_all": False, "verif_method": {"type": "Smtp"}},
                "misc": {"is_disposable": False, "is_role_account": False},
                "debug": {"duration": {"secs": 0, "nanos": 500000000}},
            },
        )

    with _reacher_with(handler) as reacher:
        stats = run_pass_one(FIXTURE, tmp_path, cfg, reacher)

    assert stats.companies == 5
    assert stats.checked > 0
    assert (tmp_path / "enriched.csv").exists()
    assert (tmp_path / "candidates.jsonl").exists()
    assert (tmp_path / "gaps.jsonl").exists()

    csv_text = (tmp_path / "enriched.csv").read_text(encoding="utf-8")
    assert "jmitchell@dasaninc.com" in csv_text

    # The Dasan row should be fully verified → NOT in gaps.jsonl.
    gaps = (tmp_path / "gaps.jsonl").read_text(encoding="utf-8")
    assert "Dasan" not in gaps


@pytest.mark.parametrize(
    "raw_name",
    ["", "   ", None],
)
def test_empty_name_does_not_crash(raw_name: str | None) -> None:
    from email_enrichment.naming import parse_name

    parse_name(raw_name or "")
