"""NormaAI API client."""

import json
import urllib.request
import urllib.error
from typing import Optional


DEFAULT_API_URL = "https://rjwaegzdfsdlnbijkark.supabase.co/functions/v1/api-query"


class NormaAIError(Exception):
    """Errore API NormaAI."""

    def __init__(self, message: str, status: int = 0, code: str = ""):
        super().__init__(message)
        self.status = status
        self.code = code


class NormaAI:
    """Client per NormaAI API.

    Args:
        api_key: API key NormaAI (inizia con "nai_")
        base_url: URL base API (opzionale)
    """

    def __init__(self, api_key: str, base_url: Optional[str] = None):
        if not api_key:
            raise ValueError("api_key obbligatoria")
        self._api_key = api_key
        self._base_url = base_url or DEFAULT_API_URL

    def _request(self, path: str, method: str = "GET", body: Optional[dict] = None) -> dict:
        url = f"{self._base_url}{path}"
        headers = {
            "X-API-Key": self._api_key,
            "Content-Type": "application/json",
        }

        data = json.dumps(body).encode("utf-8") if body else None
        req = urllib.request.Request(url, data=data, headers=headers, method=method)

        try:
            with urllib.request.urlopen(req, timeout=60) as resp:
                return json.loads(resp.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            body_text = e.read().decode("utf-8", errors="replace")
            try:
                err_data = json.loads(body_text)
                raise NormaAIError(
                    err_data.get("message", err_data.get("error", f"HTTP {e.code}")),
                    status=e.code,
                    code=err_data.get("error", ""),
                ) from e
            except json.JSONDecodeError:
                raise NormaAIError(f"HTTP {e.code}: {body_text[:200]}", status=e.code) from e

    def query(self, question: str, vertical_id: str) -> dict:
        """Domanda normativa con risposta AI e fonti citate.

        Args:
            question: Domanda in italiano (max 2000 caratteri)
            vertical_id: Verticale (lavoro|commercialista|avvocato|ingegnere|finanziario)

        Returns:
            dict con keys: answer, sources, tokens_used, vertical, response_time_ms
        """
        return self._request("/query", method="POST", body={
            "question": question,
            "vertical_id": vertical_id,
        })

    def verticals(self) -> dict:
        """Lista verticali disponibili."""
        return self._request("/verticals")

    def sources(self, vertical_id: str) -> dict:
        """Lista fonti normative per verticale."""
        return self._request(f"/sources?vertical_id={vertical_id}")

    def usage(self) -> dict:
        """Statistiche consumo API key."""
        return self._request("/usage")
