import json
import os

import httpx

EMAIL_FINDER_URL = "https://api.hunter.io/v2/email-finder"
DOMAIN_SEARCH_URL = "https://api.hunter.io/v2/domain-search"

ROLE_MAPPINGS = {
    "executives": [
        "ceo", "cto", "cfo", "coo", "cmo", "chief", "president", "vp",
        "vice president", "director", "head", "founder", "co-founder", "executive",
    ],
    "leadership": [
        "ceo", "cto", "cfo", "coo", "cmo", "chief", "president", "vp",
        "vice president", "director", "head", "founder", "co-founder",
        "executive", "manager", "lead",
    ],
    "management": ["manager", "director", "head", "lead", "chief", "vp", "vice president"],
    "engineering": ["engineer", "developer", "programmer", "architect", "cto", "technical"],
    "marketing": ["marketing", "cmo", "growth", "brand", "content", "seo", "social media"],
    "sales": ["sales", "account", "business development", "revenue", "cro"],
    "finance": ["finance", "cfo", "accounting", "financial", "controller", "treasurer"],
    "hr": ["hr", "human resources", "people", "talent", "recruiting", "chro"],
}


def _get_api_key() -> str:
    key = os.environ.get("HUNTER_API_KEY")
    if not key:
        raise ValueError("HUNTER_API_KEY not set. Get one at https://hunter.io/")
    return key


def _filter_by_role(emails: list[dict], role: str) -> list[dict]:
    """Filter email records by position/role keyword."""
    keywords = ROLE_MAPPINGS.get(role.lower(), [role.lower()])
    return [
        e for e in emails
        if e.get("position") and any(k in e["position"].lower() for k in keywords)
    ]


async def handler(params: dict) -> dict:
    """Find email addresses using Hunter.io API."""
    action = params["action"]
    domain = params["domain"]
    api_key = _get_api_key()

    if action == "find_email":
        first_name = params.get("first_name")
        last_name = params.get("last_name")
        if not first_name or not last_name:
            raise ValueError("find_email requires first_name and last_name")

        async with httpx.AsyncClient(timeout=15) as client:
            resp = await client.get(
                EMAIL_FINDER_URL,
                params={
                    "domain": domain,
                    "first_name": first_name,
                    "last_name": last_name,
                    "api_key": api_key,
                },
            )
        if resp.status_code != 200:
            raise ValueError(f"Hunter.io API error ({resp.status_code}): {resp.text}")

        data = resp.json().get("data", {})
        result = {
            "email": data.get("email"),
            "score": data.get("score"),
            "position": data.get("position"),
            "company": data.get("company"),
            "sources": [
                {"domain": s.get("domain"), "uri": s.get("uri")}
                for s in (data.get("sources") or [])[:5]
            ],
        }
        return {"result": json.dumps(result, indent=2)}

    elif action == "domain_search":
        async with httpx.AsyncClient(timeout=15) as client:
            resp = await client.get(
                DOMAIN_SEARCH_URL,
                params={"domain": domain, "api_key": api_key},
            )
        if resp.status_code != 200:
            raise ValueError(f"Hunter.io API error ({resp.status_code}): {resp.text}")

        response_data = resp.json()
        emails = response_data.get("data", {}).get("emails", [])

        role = params.get("role")
        if role:
            emails = _filter_by_role(emails, role)

        results = [
            {
                "email": e.get("value"),
                "first_name": e.get("first_name"),
                "last_name": e.get("last_name"),
                "position": e.get("position"),
                "confidence": e.get("confidence"),
            }
            for e in emails
        ]
        summary = {
            "domain": domain,
            "total_found": len(results),
        }
        if role:
            summary["role_filter"] = role
        summary["emails"] = results

        return {"result": json.dumps(summary, indent=2)}

    else:
        raise ValueError(f"Unknown action: {action}. Use 'find_email' or 'domain_search'.")
