"""HTTP client for the Evaboot API."""

import os

import httpx

DEFAULT_BASE_URL = "https://api.evaboot.com"


class EvabootClient:
    """Thin async wrapper around the Evaboot REST API."""

    def __init__(self) -> None:
        api_key = os.environ.get("EVABOOT_API_KEY")
        if not api_key:
            raise RuntimeError("EVABOOT_API_KEY environment variable is required")
        base_url = os.environ.get("EVABOOT_BASE_URL", DEFAULT_BASE_URL).rstrip("/")
        self._base = f"{base_url}/v1"
        self._headers = {"Authorization": f"Bearer {api_key}"}

    async def _request(self, method: str, path: str, **kwargs) -> dict:
        async with httpx.AsyncClient(timeout=120) as http:
            resp = await http.request(
                method,
                f"{self._base}{path}",
                headers=self._headers,
                **kwargs,
            )
            resp.raise_for_status()
            return resp.json()

    # --- Quota ---

    async def get_quota(self) -> dict:
        return await self._request("GET", "/quota/")

    # --- Email Finder ---

    async def find_email_single(
        self,
        first_name: str,
        last_name: str,
        company_name: str = "",
        company_domain: str = "",
    ) -> dict:
        return await self._request(
            "POST",
            "/email-finder/single/",
            json={
                "first_name": first_name,
                "last_name": last_name,
                "company_name": company_name,
                "company_domain": company_domain,
            },
        )

    async def find_emails_bulk(
        self,
        prospects: list[dict],
        job_name: str,
        webhook_url: str | None = None,
    ) -> dict:
        body: dict = {"prospects": prospects, "job_name": job_name}
        if webhook_url:
            body["webhook_url"] = webhook_url
        return await self._request("POST", "/email-finder/", json=body)

    async def list_email_finder_jobs(self) -> dict:
        return await self._request("GET", "/email-finder/")

    async def get_email_finder_job(self, job_id: str) -> dict:
        return await self._request("GET", f"/email-finder/{job_id}/")

    # --- Email Validation ---

    async def validate_email_single(self, email: str) -> dict:
        return await self._request(
            "POST", "/email-validation/single/", json={"email": email}
        )

    async def validate_emails_bulk(
        self,
        emails: list[str],
        job_name: str,
        webhook_url: str | None = None,
    ) -> dict:
        body: dict = {
            "prospects": [{"email": e} for e in emails],
            "job_name": job_name,
        }
        if webhook_url:
            body["webhook_url"] = webhook_url
        return await self._request("POST", "/email-validation/", json=body)

    async def list_email_validation_jobs(self) -> dict:
        return await self._request("GET", "/email-validation/")

    async def get_email_validation_job(self, job_id: str) -> dict:
        return await self._request("GET", f"/email-validation/{job_id}/")

    # --- LinkedIn Extractions ---

    async def extract_from_url(
        self,
        linkedin_url: str,
        search_name: str,
        enrich_email: str = "none",
        webhook_url: str | None = None,
    ) -> dict:
        body: dict = {
            "linkedin_url": linkedin_url,
            "search_name": search_name,
            "enrich_email": enrich_email,
        }
        if webhook_url:
            body["webhook_url"] = webhook_url
        return await self._request("POST", "/extractions/url/", json=body)

    async def extract_profiles(
        self,
        profile_ids: list[str],
        search_name: str,
        enrich_email: str = "none",
        webhook_url: str | None = None,
    ) -> dict:
        body: dict = {
            "profile_ids": profile_ids,
            "search_name": search_name,
            "enrich_email": enrich_email,
        }
        if webhook_url:
            body["webhook_url"] = webhook_url
        return await self._request("POST", "/extractions/profiles/", json=body)

    async def extract_single_profile(
        self,
        profile_id: str,
        enrich_email: str = "none",
    ) -> dict:
        return await self._request(
            "POST",
            "/extractions/single/",
            json={"profile_id": profile_id, "enrich_email": enrich_email},
        )

    # --- Search Builder ---

    async def generate_search_url(
        self, description: str, search_type: str = "LEAD"
    ) -> dict:
        return await self._request(
            "POST",
            "/search-builder/",
            json={"description": description, "search_type": search_type},
        )

    async def list_extractions(self) -> dict:
        return await self._request("GET", "/extractions/")

    async def get_extraction(self, extraction_id: str) -> dict:
        return await self._request("GET", f"/extractions/{extraction_id}/")
