"""Prospeo contact enrichment — resolves verified emails from principal names."""

import requests

PROSPEO_API_URL = "https://api.prospeo.io/enrich-person"


def enrich_via_prospeo(lead: dict, api_key: str) -> dict:
    """Call Prospeo to resolve a verified email for this lead.

    Fires when: principal_name exists AND (email is missing OR
    email came from email-prefix guessing).

    Input: principal name + domain (or company name if no domain)
    Output: updates lead with verified email, phone, job title

    Returns dict with what was found. Costs 1 credit only if
    a verified email is returned (only_verified_email: true).
    """
    name = lead.get("principal_name") or lead.get("primary_principal_name") or lead.get("greeting_name")

    if not name:
        return {"prospeo_hit": False, "reason": "no principal name"}

    # Use the best website available. Prospeo runs after Brave (Phase 3.5),
    # so brave_website is the most reliable source of the company's real site.
    # Never use `domain` — it's extracted from the email address and can be
    # a filing-service domain (e.g. incfile.com) instead of the company's site.
    website = lead.get("brave_website") or lead.get("website_url") or ""
    clean_domain = website.replace("https://", "").replace("http://", "").split("/")[0] if website else ""

    payload = {
        "only_verified_email": True,
        "data": {
            "full_name": name,
        }
    }

    if clean_domain:
        payload["data"]["company_website"] = clean_domain
    elif lead.get("name"):
        payload["data"]["company_name"] = lead["name"]

    try:
        resp = requests.post(
            PROSPEO_API_URL,
            json=payload,
            headers={
                "X-KEY": api_key,
                "Content-Type": "application/json",
            },
            timeout=10,
        )
        body = resp.json()

        if body.get("error"):
            code = body.get("error_code", "")
            return {"prospeo_hit": False, "reason": f"API error: {code}"}

        if not body.get("person"):
            return {"prospeo_hit": False, "reason": "person not found"}

        person = body["person"]
        email_info = person.get("email", {})
        email = email_info.get("email")
        status = email_info.get("status")

        if email and status == "VERIFIED":
            return {
                "prospeo_hit": True,
                "prospeo_email": email,
                "prospeo_email_status": status,
                "prospeo_first_name": person.get("first_name"),
                "prospeo_last_name": person.get("last_name"),
            }
        else:
            return {"prospeo_hit": False, "reason": "no verified email found"}

    except Exception as e:
        return {"prospeo_hit": False, "reason": str(e)}
