"""Clay 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 ClayProvider(BaseProvider):
    """Clay API wrapper for enrichment tasks."""

    name = "clay"
    kind = "enrichment"

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

    def find_email(self, first: str, last: str, domain: str) -> ProviderResult:
        """Find email via Clay endpoint or fallback to mock."""
        if not self.api_key:
            return self._fallback.find_email(first, last, domain)
        try:
            response = requests.post(
                "https://api.clay.com/v1/email/find",
                json={"first_name": first, "last_name": last, "domain": domain},
                headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
                timeout=10,
            )
            response.raise_for_status()
            payload = response.json() if isinstance(response.json(), dict) else {}
            email = payload.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=payload, 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 via Clay endpoint or fallback to mock."""
        if not self.api_key:
            return self._fallback.enrich_contact(email)
        try:
            response = requests.post(
                "https://api.clay.com/v1/enrich/contact",
                json={"email": email},
                headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
                timeout=10,
            )
            response.raise_for_status()
            payload = response.json() if isinstance(response.json(), dict) else {}
            payload["email"] = payload.get("email") or email
            return ProviderResult(ok=True, provider=self.name, data=payload, confidence=0.7)
        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 Clay API appears reachable."""
        if not self.api_key:
            return self._fallback.health_check()
        try:
            response = requests.get(
                "https://api.clay.com/v1/health",
                headers={"Authorization": f"Bearer {self.api_key}"},
                timeout=10,
            )
            return response.status_code < 500
        except Exception:  # noqa: BLE001
            return False
