"""Constants and status helpers for FullEnrich integrations."""

from __future__ import annotations

from enum import Enum
from typing import Optional


class FullEnrichAPIVersion(str, Enum):
    V1 = "v1"
    V2 = "v2"


API_BASE_V1 = "https://app.fullenrich.com/api/v1"
API_BASE_V2 = "https://app.fullenrich.com/api/v2"

CONTACT_BULK_PATH = "/contact/enrich/bulk"
COMPANY_ENRICH_PATH = "/company/enrich"
CREDITS_PATH = "/account/credits"
VERIFY_PATH = "/account/keys/verify"

DEFAULT_API_VERSION = FullEnrichAPIVersion.V2
DEFAULT_CONTACT_FIELDS = ["contact.emails", "contact.phones"]
DEFAULT_CONTACT_OUTPUT_FIELDS = [
    "work_email",
    "personal_email",
    "phone",
    "title",
    "linkedin_url",
    "location",
    "company_name",
    "company_domain",
]
CHECK_PARAMS = {"checkLinkedinUrl": "false", "checkDomain": "false"}

# Map UI output field names to FullEnrich enrich_fields
UI_FIELD_TO_ENRICH_FIELD = {
    "work_email": "contact.emails",
    "personal_email": "contact.personal_emails",
    "phone": "contact.phones",
    # These fields come with the response automatically, no need to request
    "title": None,
    "linkedin_url": None,
    "location": None,
    "company_name": None,
    "company_domain": None,
}


def map_output_fields_to_enrich_fields(output_fields: list[str]) -> list[str]:
    """Map UI output field names to FullEnrich API enrich_fields."""
    enrich_fields = set()
    for field in output_fields:
        mapped = UI_FIELD_TO_ENRICH_FIELD.get(field)
        if mapped:
            enrich_fields.add(mapped)
    # Always include at least default fields if none mapped
    if not enrich_fields:
        return list(DEFAULT_CONTACT_FIELDS)
    return sorted(enrich_fields)


def normalize_api_version(value: Optional[str]) -> FullEnrichAPIVersion:
    raw = str(value or "").strip().lower()
    if raw in {"v2", "2"}:
        return FullEnrichAPIVersion.V2
    return FullEnrichAPIVersion.V1


def api_base(version: FullEnrichAPIVersion | str | None = None) -> str:
    ver = normalize_api_version(str(version or DEFAULT_API_VERSION.value))
    return API_BASE_V2 if ver == FullEnrichAPIVersion.V2 else API_BASE_V1


def build_url(path: str, version: FullEnrichAPIVersion | str | None = None) -> str:
    base = api_base(version).rstrip("/")
    return f"{base}{path}"


def parse_credit_balance(payload: dict) -> Optional[int]:
    if not isinstance(payload, dict):
        return None
    balance = payload.get("balance")
    if balance in (None, ""):
        balance = payload.get("credits")
    try:
        return int(balance) if balance is not None else None
    except (TypeError, ValueError):
        return None

CONTACT_ERROR_STATUSES = {"failed", "error", "no_credits", "credits_insufficient", "rate_limit"}
CONTACT_NOT_FOUND_STATUSES = {"not_found", "no_match", "no_data"}

JOB_PENDING_STATUSES = {"CREATED", "IN_PROGRESS", "RATE_LIMIT", "SUBMITTED"}
JOB_TERMINAL_STATUSES = {
    "FINISHED",
    "COMPLETED",
    "FAILED",
    "CANCELED",
    "CREDITS_INSUFFICIENT",
    "NO_CREDITS",
    "UNKNOWN",
    "TIMEOUT",
}
JOB_FAILURE_STATUSES = {
    "FAILED",
    "CANCELED",
    "CREDITS_INSUFFICIENT",
    "NO_CREDITS",
    "UNKNOWN",
    "TIMEOUT",
}


def normalize_job_status(status: Optional[str]) -> str:
    raw = str(status or "").upper()
    if raw in {"FINISHED", "COMPLETED"}:
        return "completed"
    if raw in {"FAILED", "CANCELED", "UNKNOWN"}:
        return "failed"
    if raw in {"CREDITS_INSUFFICIENT", "NO_CREDITS"}:
        return "no_credits"
    if raw in {"RATE_LIMIT"}:
        return "rate_limit"
    if raw in {"CREATED", "IN_PROGRESS", "SUBMITTED"}:
        return "pending"
    if raw in {"TIMEOUT"}:
        return "timeout"
    return raw.lower() if raw else "unknown"


def is_terminal_status(status: Optional[str]) -> bool:
    raw = str(status or "").upper()
    return raw in JOB_TERMINAL_STATUSES
