"""HTTP client for A2RAG API."""
from __future__ import annotations
import json, urllib.request, urllib.error
from typing import Any, Dict


class APIClient:
    def __init__(self, api_key: str, base_url: str, timeout: int = 10):
        self.api_key  = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout  = timeout

    @property
    def _headers(self):
        return {
            "Content-Type": "application/json",
            "X-API-Key":    self.api_key,
        }

    def post(self, path: str, payload: Dict) -> Dict:
        data = json.dumps(payload).encode()
        req  = urllib.request.Request(
            self.base_url + path, data=data,
            headers=self._headers, method="POST",
        )
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as r:
                return json.loads(r.read())
        except urllib.error.HTTPError as e:
            body = e.read().decode()
            if e.code == 401:
                raise AuthError("Invalid API key. Check https://a2rag.com/dashboard")
            if e.code == 429:
                raise RateLimitError("Rate limit exceeded. Upgrade your plan.")
            if e.code == 422:
                raise ValidationError(f"Invalid request: {body}")
            raise APIError(f"API error {e.code}: {body}")
        except urllib.error.URLError as e:
            raise ConnectionError(f"Cannot reach A2RAG API: {e}")

    def get(self, path: str) -> Dict:
        req = urllib.request.Request(
            self.base_url + path, headers=self._headers,
        )
        with urllib.request.urlopen(req, timeout=self.timeout) as r:
            return json.loads(r.read())


def _normalize_contexts(contexts):
    result = []
    for ctx in contexts:
        if isinstance(ctx, str):
            result.append(ctx)
        elif hasattr(ctx, "page_content"):
            result.append(str(ctx.page_content))
        elif hasattr(ctx, "text"):
            result.append(str(ctx.text))
        elif isinstance(ctx, dict):
            result.append(str(ctx.get("text") or ctx.get("content") or ctx.get("page_content") or str(ctx)))
        else:
            result.append(str(ctx))
    return result


class A2RAGError(Exception): pass
class AuthError(A2RAGError): pass
class RateLimitError(A2RAGError): pass
class ValidationError(A2RAGError): pass
class APIError(A2RAGError): pass
class ConnectionError(A2RAGError): pass
