"""Re-enrich emails for existing Baserow leads using Reacher API.

Usage: uv run python scripts/re_enrich_emails.py
"""

from __future__ import annotations

import asyncio

import httpx
import structlog

from src.config import get_settings
from src.enrichment import (
    _email_generic_ping,
    _email_guess_reacher,
)

log = structlog.get_logger()


async def re_enrich_emails() -> None:
    settings = get_settings()

    if not settings.reacher_url:
        print("REACHER_URL non configuré. Ajoute REACHER_URL et REACHER_SECRET dans tes env vars.")
        return

    # 1. Fetch all leads from Baserow
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"{settings.baserow_base_url}/api/database/rows/table/{settings.baserow_table_id}/",
            params={"user_field_names": "true", "size": 200},
            headers={"Authorization": f"Token {settings.baserow_token}"},
            timeout=30.0,
        )
        resp.raise_for_status()
        leads = resp.json()["results"]

    # 2. Filter leads without email
    no_email = [l for l in leads if not l.get("Email Contact")]
    print(f"Total leads: {len(leads)}, sans email: {len(no_email)}\n")

    found = 0
    errors = 0

    async with httpx.AsyncClient() as http_client:
        for lead in no_email:
            domain = lead.get("Domaine", "")
            first = lead.get("Prenom", "")
            last = lead.get("Nom", "")
            row_id = lead["id"]
            name = lead.get("Entreprise", domain)

            if not domain:
                continue

            print(f"[{name}] {domain} — {first} {last}".strip())

            email = ""

            # Try guessing if we have director name
            if first and last:
                email, _status = await _email_guess_reacher(http_client, first, last, domain)
                if email:
                    print(f"  > Guess: {email}")

            # Fallback: generic ping
            if not email:
                email, _status = await _email_generic_ping(http_client, domain)
                if email:
                    print(f"  > Generic: {email}")

            if not email:
                print(f"  X Aucun email trouve")
                continue

            # Update Baserow
            found += 1
            resp = await http_client.patch(
                f"{settings.baserow_base_url}/api/database/rows/table/{settings.baserow_table_id}/{row_id}/",
                params={"user_field_names": "true"},
                headers={"Authorization": f"Token {settings.baserow_token}"},
                json={"Email Contact": email},
                timeout=15.0,
            )
            if resp.status_code == 200:
                print(f"  > Baserow OK")
            else:
                print(f"  ! Baserow error: {resp.status_code}")
                errors += 1

            await asyncio.sleep(0.5)

    print(f"\n=== Resultat: {found} emails trouves / {len(no_email)} leads sans email ({errors} erreurs) ===")


if __name__ == "__main__":
    asyncio.run(re_enrich_emails())
