"""HTTP client for the ADP External API."""

import os
import httpx


class ADPClient:
    """Client for the ADP Deep Analysis external API."""

    def __init__(self, api_url: str | None = None, api_key: str | None = None):
        self.api_url = (api_url or os.environ.get("ADP_API_URL", "https://aidetectorpro.com")).rstrip("/")
        self.api_key = api_key or os.environ.get("ADP_API_KEY", "")

        if not self.api_key:
            raise ValueError(
                "ADP_API_KEY is required. Set it as an environment variable "
                "or pass it to the ADPClient constructor."
            )

    async def analyze(self, document_text: str, document_name: str = "Untitled") -> dict:
        """Run Deep Analysis on document text. Returns the raw API response dict."""
        async with httpx.AsyncClient(timeout=300) as client:
            response = await client.post(
                f"{self.api_url}/api/v1/external/analyze",
                json={
                    "document_text": document_text,
                    "document_name": document_name,
                },
                headers={
                    "Authorization": f"Bearer {self.api_key}",
                    "Content-Type": "application/json",
                },
            )

        if response.status_code == 401:
            raise RuntimeError("Invalid API key. Check your ADP_API_KEY.")
        if response.status_code == 403:
            raise RuntimeError("API key has been revoked.")
        if response.status_code == 429:
            raise RuntimeError("Rate limit exceeded. Wait and try again.")
        if response.status_code != 200:
            detail = response.json().get("detail", response.text) if response.headers.get("content-type", "").startswith("application/json") else response.text
            raise RuntimeError(f"ADP API error ({response.status_code}): {detail}")

        return response.json()
