"""
People Data Labs (PDL) enrichment client.

Supports company enrichment using the PDL v5 API.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

import click
from g_gremlin.base import AuthenticationError, BaseIntegration, IntegrationError, RateLimitError, RetryConfig
from g_gremlin.credentials import resolve_credentials
from g_gremlin.credentials.provider import CredentialProvider, SecretNotFoundError

PDL_DEFAULT_BASE = "https://api.peopledatalabs.com"
PDL_COMPANY_ENRICH_PATH = "/v5/company/enrich"
DEFAULT_RETRY_CONFIG = RetryConfig(max_attempts=3, base_delay=1.0, max_delay=8.0)


class PdlError(RuntimeError):
    """Raised when People Data Labs enrichment fails."""


def _load_api_settings(
    credential_provider: CredentialProvider | None = None,
    api_key: Optional[str] = None,
    api_base: Optional[str] = None,
) -> tuple[str, str]:
    """Load PDL API key (and optional api_base) via CredentialProvider."""

    if api_key and api_base:
        return api_key, api_base

    provider = credential_provider or CredentialProvider()
    try:
        creds = resolve_credentials(
            "pdl",
            required_keys=["api_key"],
            optional_keys=["api_base"],
            credential_provider=provider,
        )
        return creds["api_key"], creds.get("api_base") or PDL_DEFAULT_BASE
    except SecretNotFoundError:
        raise click.ClickException(
            "People Data Labs not configured. Set up with:\n"
            "  g-gremlin auth set pdl                    # Store in keychain\n"
            "  export G_GREMLIN_PDL_API_KEY=your-key     # Or use env var"
        )


def _build_params(company: str) -> Dict[str, Any]:
    """
    Decide best query params for company enrichment.

    If company looks like a domain (contains a dot, no spaces), use website.
    Otherwise, use name.
    """
    company_clean = (company or "").strip()
    if not company_clean:
        return {}

    if "." in company_clean and " " not in company_clean:
        return {"website": company_clean, "pretty": "false"}
    return {"name": company_clean, "pretty": "false"}


def _extract_company_fields(data: Dict[str, Any]) -> Dict[str, Any]:
    """Normalize PDL company response to common fields."""
    if not data:
        return {}
    location = data.get("location") or {}
    return {
        "name": data.get("name"),
        "domain": data.get("website") or data.get("domain"),
        "website": data.get("website"),
        "industry": data.get("industry"),
        "employee_count": data.get("employee_count") or data.get("size"),
        "employee_range": data.get("employee_range"),
        "linkedin_url": data.get("linkedin_url") or data.get("profiles", {}).get("linkedin"),
        "founded_year": data.get("founded"),
        "revenue": data.get("revenue"),
        "naics": data.get("naics"),
        "sic": data.get("sic"),
        "country": location.get("country"),
        "region": location.get("region"),
        "locality": location.get("locality"),
    }


class PdlClient(BaseIntegration):
    """PDL client using BaseIntegration."""

    SERVICE_NAME = "pdl"

    def __init__(
        self,
        credential_provider: CredentialProvider | None = None,
        api_key: Optional[str] = None,
        api_base: Optional[str] = None,
        retry_config: RetryConfig | None = None,
    ) -> None:
        super().__init__(credential_provider=credential_provider, default_retry_config=retry_config or DEFAULT_RETRY_CONFIG)
        self.api_key, self.api_base = _load_api_settings(credential_provider, api_key, api_base)

    def enrich_company(self, company: str, fields: Optional[List[str]] = None) -> Dict[str, Any]:
        params = _build_params(company)
        if not params:
            return {}

        headers = {"X-API-Key": self.api_key}
        url = f"{self.api_base.rstrip('/')}{PDL_COMPANY_ENRICH_PATH}"
        try:
            resp = self._get(url, params=params, headers=headers, allow_statuses=(404,))
        except (AuthenticationError, RateLimitError, IntegrationError) as exc:
            raise PdlError(str(exc)) from exc

        if resp.status_code == 404:
            return {}

        try:
            data = resp.json()
        except Exception as exc:  # pragma: no cover - network parsing
            raise PdlError(f"Failed to parse PDL response: {exc}") from exc

        if isinstance(data, dict):
            if "data" in data and isinstance(data["data"], dict):
                data = data["data"]

        normalized = _extract_company_fields(data if isinstance(data, dict) else {})
        if fields:
            return {k: normalized.get(k) for k in fields if k in normalized}
        return normalized


def enrich_company(company: str, fields: Optional[List[str]] = None) -> Dict[str, Any]:
    """
    Enrich company by domain/name using People Data Labs.

    Args:
        company: Company domain or name.
        fields: Optional subset of fields to return.

    Returns:
        Dict of normalized company attributes, or {} if no match.
    """
    company_clean = (company or "").strip()
    if not company_clean:
        return {}

    client = PdlClient()
    try:
        return client.enrich_company(company_clean, fields)
    except PdlError as exc:
        raise click.ClickException(str(exc)) from exc


__all__ = [
    "PdlError",
    "PdlClient",
    "enrich_company",
]
