"""Async HTTP client wrapping the suss. production API."""

from __future__ import annotations

import os

import httpx

DEFAULT_API_URL = "https://suss-api-353192091596.us-central1.run.app"
TIMEOUT = httpx.Timeout(30.0, connect=5.0)


class SussClient:
    """Thin async wrapper around the suss. REST API."""

    def __init__(self) -> None:
        self.base_url = os.environ.get("SUSS_API_URL", DEFAULT_API_URL).rstrip("/")
        self.api_key = os.environ.get("SUSS_API_KEY", "")
        self._client: httpx.AsyncClient | None = None

    async def _get_client(self) -> httpx.AsyncClient:
        if self._client is None or self._client.is_closed:
            headers: dict[str, str] = {"User-Agent": "suss-mcp/0.1.0"}
            if self.api_key:
                headers["Authorization"] = f"Bearer {self.api_key}"
            self._client = httpx.AsyncClient(
                base_url=self.base_url,
                headers=headers,
                timeout=TIMEOUT,
            )
        return self._client

    async def close(self) -> None:
        if self._client and not self._client.is_closed:
            await self._client.aclose()

    async def check_trust(self, domain: str) -> dict:
        """GET /api/trust/{domain}"""
        client = await self._get_client()
        resp = await client.get(f"/api/trust/{domain}")
        resp.raise_for_status()
        return resp.json()

    async def scan_text(self, text: str, channel: str = "default") -> dict:
        """POST /api/score with text payload."""
        client = await self._get_client()
        payload: dict = {"text": text, "channel": channel, "source": "mcp"}
        resp = await client.post("/api/score", json=payload)
        resp.raise_for_status()
        return resp.json()

    async def scan_url(self, url: str, text: str = "") -> dict:
        """POST /api/score with url (and optional text)."""
        client = await self._get_client()
        payload: dict = {"url": url, "source": "mcp"}
        if text:
            payload["text"] = text
        resp = await client.post("/api/score", json=payload)
        resp.raise_for_status()
        return resp.json()

    async def batch_trust(self, domains: list[str]) -> dict:
        """POST /api/trust/batch"""
        client = await self._get_client()
        resp = await client.post("/api/trust/batch", json={"domains": domains})
        resp.raise_for_status()
        return resp.json()

    async def report_feedback(
        self,
        request_id: str,
        feedback_type: str,
        original_text: str = "",
        original_score: float = 0.0,
        user_comment: str = "",
    ) -> dict:
        """POST /api/feedback"""
        client = await self._get_client()
        payload = {
            "request_id": request_id,
            "feedback_type": feedback_type,
            "original_text": original_text,
            "original_score": original_score,
        }
        if user_comment:
            payload["user_comment"] = user_comment
        resp = await client.post("/api/feedback", json=payload)
        resp.raise_for_status()
        return resp.json()

    async def lookup_entity(self, entity_type: str, value: str) -> dict:
        """GET /api/entity/{entity_type}/{value}"""
        client = await self._get_client()
        resp = await client.get(f"/api/entity/{entity_type}/{value}")
        resp.raise_for_status()
        return resp.json()

    async def verify(
        self,
        text: str = "",
        url: str = "",
        include_image: bool = False,
    ) -> dict:
        """POST /api/v1/verify — fast agent-optimized endpoint."""
        client = await self._get_client()
        payload: dict = {"source": "mcp"}
        if text:
            payload["text"] = text
        if url:
            payload["url"] = url
        if include_image:
            payload["include_image"] = True
        resp = await client.post("/api/v1/verify", json=payload)
        resp.raise_for_status()
        return resp.json()
