"""Anthropic provider — Claude API."""

from __future__ import annotations

import json
import os
import time
import urllib.error
import urllib.request

from orxaq.orchestration.providers.base import LLMProvider, LLMResponse


class AnthropicProvider(LLMProvider):
    """Provider for Anthropic Claude API."""

    name = "anthropic"

    def __init__(
        self,
        auth: str | None = None,
        models: list[str] | None = None,
    ) -> None:
        self._auth = auth if auth is not None else os.environ.get("ANTHROPIC_API_KEY", "")
        self.models = models or ["claude-sonnet-4-5-20250929"]
        self.endpoint = "https://api.anthropic.com/v1/messages"

    def generate(
        self,
        prompt: str,
        model: str | None = None,
        max_tokens: int = 1024,
        temperature: float = 0.7,
    ) -> LLMResponse:
        """Generate via Anthropic Messages API."""
        if not self._auth:
            return LLMResponse(
                text="",
                model=model or self.models[0],
                provider=self.name,
                metadata={"error": "ANTHROPIC_API_KEY not set"},
            )

        use_model = model or self.models[0]
        payload = {
            "model": use_model,
            "max_tokens": max_tokens,
            "messages": [{"role": "user", "content": prompt}],
        }

        start = time.monotonic()
        data = json.dumps(payload).encode("utf-8")
        req = urllib.request.Request(
            self.endpoint,
            data=data,
            headers={
                "Content-Type": "application/json",
                "x-api-key": self._auth,
                "anthropic-version": "2023-06-01",
            },
        )

        try:
            with urllib.request.urlopen(req, timeout=120) as resp:
                result = json.loads(resp.read())
        except (urllib.error.URLError, OSError) as e:
            return LLMResponse(
                text="",
                model=use_model,
                provider=self.name,
                metadata={"error": str(e)},
            )

        elapsed = (time.monotonic() - start) * 1000

        text = ""
        for block in result.get("content", []):
            if block.get("type") == "text":
                text += block.get("text", "")

        usage = result.get("usage", {})
        return LLMResponse(
            text=text,
            model=use_model,
            provider=self.name,
            input_tokens=usage.get("input_tokens", 0),
            output_tokens=usage.get("output_tokens", 0),
            latency_ms=elapsed,
        )

    def health_check(self) -> dict:
        """Check if API key is configured."""
        if not self._auth:
            return {
                "healthy": False,
                "provider": self.name,
                "models": self.models,
                "error": "ANTHROPIC_API_KEY not set",
            }
        return {
            "healthy": True,
            "provider": self.name,
            "models": self.models,
        }
