"""Anthropic judge using structured outputs."""

from __future__ import annotations

import logging

from evalkit.judges.base import BaseJudge
from evalkit.models import JudgeResponse
from evalkit.prompts import SYSTEM_PROMPT

logger = logging.getLogger(__name__)


class AnthropicJudge(BaseJudge):
    """Judge using ``messages.parse(output_format=JudgeResponse)``."""

    def __init__(
        self,
        model: str = "claude-haiku-4-5-20251001",
        api_key: str | None = None,
        max_tokens: int = 1024,
        timeout: float = 60.0,
    ) -> None:
        try:
            import anthropic  # noqa: F401
        except ImportError as exc:
            raise ImportError("Install anthropic: pip install evalkit-llm[anthropic]") from exc

        self.model = model
        self.api_key = api_key
        self.max_tokens = max_tokens
        self.timeout = timeout

    def evaluate(self, prompt: str) -> JudgeResponse:
        import anthropic

        logger.debug("AnthropicJudge calling model=%s, prompt_len=%d", self.model, len(prompt))
        client = (
            anthropic.Anthropic(api_key=self.api_key, timeout=self.timeout)
            if self.api_key
            else anthropic.Anthropic(timeout=self.timeout)
        )

        response = client.messages.parse(
            model=self.model,
            max_tokens=self.max_tokens,
            system=SYSTEM_PROMPT,
            messages=[{"role": "user", "content": prompt}],
            output_format=JudgeResponse,
        )

        parsed = response.parsed_output
        result = JudgeResponse(
            score=max(0.0, min(1.0, parsed.score)),
            reason=parsed.reason,
        )
        logger.debug("AnthropicJudge response: score=%.3f, reason=%s", result.score, result.reason[:100])
        return result
