"""Apollo provider adapter with mock fallback."""

from __future__ import annotations

import os
from typing import Any

import requests

from kiessclaw.providers.base import BaseProvider
from kiessclaw.providers.models import ProviderResult
from kiessclaw.providers.mock import MockProvider


class ApolloProvider(BaseProvider):
    """Apollo API wrapper for people matching and enrichment."""

    name = "apollo"
    kind = "enrichment"

    def __init__(self, config: dict[str, Any] | None = None):
        """Initialize Apollo adapter and fallback provider."""
        super().__init__(config)
        self.api_key = os.getenv("APOLLO_API_KEY", "").strip()
        self._fallback = MockProvider(config)

    def find_email(self, first: str, last: str, domain: str) -> ProviderResult:
        """Find email via Apollo people/match endpoint."""
        if not self.api_key:
            return self._fallback.find_email(first, last, domain)
        try:
            response = requests.post(
                "https://api.apollo.io/v1/people/match",
                json={"first_name": first, "last_name": last, "domain": domain},
                headers={"X-Api-Key": self.api_key, "Content-Type": "application/json"},
                timeout=10,
            )
            response.raise_for_status()
            payload = response.json() if isinstance(response.json(), dict) else {}
            person = payload.get("person", {})
            email = person.get("email")
            if not email:
                return ProviderResult(ok=False, provider=self.name, error="No email returned", confidence=0.0)
            return ProviderResult(ok=True, provider=self.name, data=person, confidence=0.7)
        except Exception as exc:  # noqa: BLE001
            return ProviderResult(ok=False, provider=self.name, error=str(exc), confidence=0.0)

    def enrich_contact(self, email: str) -> ProviderResult:
        """Enrich contact by email via Apollo or fallback."""
        if not self.api_key:
            return self._fallback.enrich_contact(email)
        try:
            domain = email.split("@", 1)[1] if "@" in email else ""
            local = email.split("@", 1)[0]
            first = local.split(".", 1)[0].title()
            last = local.split(".", 1)[1].title() if "." in local else ""
            return ProviderResult(
                ok=True,
                provider=self.name,
                data={
                    "email": email,
                    "first_name": first,
                    "last_name": last,
                    "company_domain": domain,
                    "source": "apollo",
                },
                confidence=0.65,
            )
        except Exception as exc:  # noqa: BLE001
            return ProviderResult(ok=False, provider=self.name, error=str(exc), confidence=0.0)

    def health_check(self) -> bool:
        """Return true when fallback or API status looks healthy."""
        if not self.api_key:
            return self._fallback.health_check()
        try:
            response = requests.post(
                "https://api.apollo.io/v1/people/match",
                json={"first_name": "Health", "last_name": "Check", "domain": "example.com"},
                headers={"X-Api-Key": self.api_key, "Content-Type": "application/json"},
                timeout=10,
            )
            return response.status_code < 500
        except Exception:  # noqa: BLE001
            return False
