from __future__ import annotations

from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field

from ...config.enrichment import ENRICHMENT_ENABLED
from fmatch.saas.integrations.people_data_labs import (
    PeopleDataLabsAdapter,
)
from ..v1.pdl import _extract_field_value
from ..v1.deps import require_api_key


def require_enrichment_enabled():
    if not ENRICHMENT_ENABLED:
        raise HTTPException(
            status_code=404,
            detail="Enrichment features are not currently available",
        )


router = APIRouter(
    prefix="/api/v2/enrichment",
    tags=["enrichment"],
    dependencies=[Depends(require_enrichment_enabled)],
)


class AccountIntelRequest(BaseModel):
    domain: Optional[str] = None
    name: Optional[str] = None
    job_title_filter: Optional[str] = None
    job_location: Optional[str] = None
    max_jobs: int = Field(default=10, ge=1, le=100)
    company_fields: List[str] = Field(
        default_factory=lambda: [
            "name",
            "domain",
            "industry",
            "employee_count",
            "estimated_revenue",
            "technologies",
            "linkedin_url",
        ]
    )


class ContactContextRequest(BaseModel):
    email: Optional[str] = None
    first_name: Optional[str] = None
    last_name: Optional[str] = None
    company: Optional[str] = None
    linkedin_url: Optional[str] = None
    include_company: bool = True


@router.post("/account-intelligence")
async def account_intelligence(
    req: AccountIntelRequest,
    api_ctx=Depends(require_api_key),
) -> Dict[str, Any]:
    """Composite: company basics + technologies + recent jobs."""
    from ...middleware.quota_checker import get_quota
    from ...db import get_session

    adapter = PeopleDataLabsAdapter()
    if not adapter.available():
        raise HTTPException(status_code=503, detail="PDL API key not configured")

    # Check enrichment credit quota
    account_id = api_ctx.account_id
    if account_id:
        async for db in get_session():
            try:
                quota = await get_quota(str(account_id), db)
                check_result = quota.check_can_run(
                    estimated_rows=0, credits_needed=1
                )  # 1 credit per company enrichment

                if not check_result["allowed"]:
                    raise HTTPException(
                        status_code=402,  # Payment Required
                        detail={
                            "error": "insufficient_credits",
                            "message": check_result["message"],
                            "remaining_credits": check_result.get(
                                "remaining_credits", 0
                            ),
                            "upgrade_url": "/pricing",
                        },
                    )
            except HTTPException:
                raise
            except Exception:
                # Log but don't block on quota check errors
                pass

    # Company enrichment
    comp = adapter.enrich_company(name=req.name, domain=req.domain)
    if "error" in comp:
        raise HTTPException(status_code=500, detail=comp["error"])
    company_data = comp.get("data") or {}

    # Select fields
    company_out: Dict[str, Any] = {}
    for f in req.company_fields:
        company_out[f] = _extract_field_value(company_data, f)

    # Jobs
    jobs = []
    if company_out.get("name") or req.domain:
        jp = adapter.get_job_postings(
            company_name=company_out.get("name") or req.name,
            company_domain=req.domain,
            job_title=req.job_title_filter,
            location=req.job_location,
            size=req.max_jobs,
        )
        if "error" not in jp:
            for item in jp.get("data", [])[: req.max_jobs]:
                jobs.append(
                    {
                        "job_title": _extract_field_value(item, "job_title"),
                        "location": _extract_field_value(item, "location"),
                        "posted_at": _extract_field_value(item, "posted_at"),
                        "url": _extract_field_value(item, "url"),
                    }
                )

    # Record credit usage
    if account_id:
        async for db in get_session():
            try:
                from ...middleware.quota_checker import record_quota_usage

                await record_quota_usage(
                    account_id=str(account_id),
                    db=db,
                    rows_returned=0,
                    credits_consumed=1,  # 1 credit per company enrichment
                    used_grace=False,
                )
            except Exception:
                # Log but don't fail the request
                pass

    return {
        "ok": True,
        "company": company_out,
        "jobs": jobs,
    }


@router.post("/contact-context")
async def contact_context(
    req: ContactContextRequest,
    api_ctx=Depends(require_api_key),
) -> Dict[str, Any]:
    """Composite: person enrichment + current employment + optional company summary."""
    from ...middleware.quota_checker import get_quota, record_quota_usage
    from ...db import get_session

    adapter = PeopleDataLabsAdapter()
    if not adapter.available():
        raise HTTPException(status_code=503, detail="PDL API key not configured")

    # Check enrichment credit quota
    account_id = api_ctx.account_id
    credits_needed = 2 if req.include_company else 1  # Person + optional company
    if account_id:
        async for db in get_session():
            try:
                quota = await get_quota(str(account_id), db)
                check_result = quota.check_can_run(
                    estimated_rows=0, credits_needed=credits_needed
                )

                if not check_result["allowed"]:
                    raise HTTPException(
                        status_code=402,
                        detail={
                            "error": "insufficient_credits",
                            "message": check_result["message"],
                            "remaining_credits": check_result.get(
                                "remaining_credits", 0
                            ),
                            "upgrade_url": "/pricing",
                        },
                    )
            except HTTPException:
                raise
            except Exception:
                pass

    # Person enrichment
    person = adapter.enrich_person(
        email=req.email,
        name=None,
        first_name=req.first_name,
        last_name=req.last_name,
        company=req.company,
        linkedin_url=req.linkedin_url,
    )
    if "error" in person:
        raise HTTPException(status_code=500, detail=person["error"])
    pdata = person.get("data") or {}

    out_person = {
        "full_name": pdata.get("full_name")
        or (
            " ".join(filter(None, [pdata.get("first_name"), pdata.get("last_name")]))
        ).strip(),
        "work_email": _extract_field_value(pdata, "work_email"),
        "phone_numbers": _extract_field_value(pdata, "phone_numbers"),
        "job_title": _extract_field_value(pdata, "job_title"),
        "job_company_name": _extract_field_value(pdata, "job_company_name"),
        "linkedin_url": _extract_field_value(pdata, "linkedin_url"),
    }

    company_summary: Optional[Dict[str, Any]] = None
    if req.include_company:
        employer = out_person.get("job_company_name") or req.company
        if employer:
            comp = adapter.enrich_company(name=employer)
            if "error" not in comp:
                cdata = comp.get("data") or {}
                company_summary = {
                    "name": _extract_field_value(cdata, "name"),
                    "domain": _extract_field_value(cdata, "domain")
                    or _extract_field_value(cdata, "website"),
                    "industry": _extract_field_value(cdata, "industry"),
                    "employee_count": _extract_field_value(cdata, "employee_count"),
                    "technologies": _extract_field_value(cdata, "technologies"),
                    "linkedin_url": _extract_field_value(cdata, "linkedin_url"),
                }

    # Record credit usage
    if account_id:
        async for db in get_session():
            try:
                await record_quota_usage(
                    account_id=str(account_id),
                    db=db,
                    rows_returned=0,
                    credits_consumed=credits_needed,
                    used_grace=False,
                )
            except Exception:
                pass

    return {"ok": True, "person": out_person, "company": company_summary}
