"""Hunter 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 HunterProvider(BaseProvider):
    """Hunter API wrapper for email finding and enrichment."""

    name = "hunter"
    kind = "email_finder"

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

    def find_email(self, first: str, last: str, domain: str) -> ProviderResult:
        """Find email via Hunter or fallback to mock when key is missing."""
        if not self.api_key:
            return self._fallback.find_email(first, last, domain)

        try:
            response = requests.get(
                "https://api.hunter.io/v2/email-finder",
                params={
                    "domain": domain,
                    "first_name": first,
                    "last_name": last,
                    "api_key": self.api_key,
                },
                timeout=10,
            )
            response.raise_for_status()
            payload = response.json()
            data = payload.get("data", {}) if isinstance(payload, dict) else {}
            email = data.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=data, confidence=float(data.get("score", 75) / 100))
        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:
        """Return lightweight enrichment from email metadata."""
        if not self.api_key:
            return self._fallback.enrich_contact(email)
        try:
            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, "source": "hunter"},
                confidence=0.6,
            )
        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 configured API appears reachable."""
        if not self.api_key:
            return self._fallback.health_check()
        try:
            response = requests.get(
                "https://api.hunter.io/v2/account",
                params={"api_key": self.api_key},
                timeout=10,
            )
            return response.status_code < 500
        except Exception:  # noqa: BLE001
            return False
