"""ContradictionCheck: Detect self-contradictions across conversation turns."""

from __future__ import annotations

from typing import TYPE_CHECKING

from ai_qa.checks.registry import register
from ai_qa.core.check import BaseCheck
from ai_qa.core.result import CheckResult
from ai_qa.exceptions import ContextValidationError
from ai_qa.providers import get_provider

if TYPE_CHECKING:
    from ai_qa.core.context import Context

JUDGE_PROMPT = """You are an expert at detecting self-contradictions in
conversational AI responses.

Given a multi-turn conversation, analyze:
- Does the AI contradict something it said earlier?
- Are there logical inconsistencies across turns?
- Does the AI flip positions or change facts?

Score: 1.0 = no contradictions, 0.0 = many contradictions detected

Respond with a JSON object:
{
  "score": <float 0.0-1.0>,
  "evidence": "<list of contradictions found or confirmation of consistency>"
}
"""


@register("contradiction")
class ContradictionCheck(BaseCheck):
    """Check for self-contradictions across conversation turns.

    Detects when the AI contradicts itself or changes positions within
    a multi-turn conversation.

    Args:
        threshold: Score threshold for passing (default 0.7).
    """

    requires_llm = True
    version = "1.0.0"
    description = "Detect self-contradictions across conversation turns"

    def validate_context(self, ctx: Context) -> None:
        """Validate that conversation history is provided.

        Args:
            ctx: The context to validate.

        Raises:
            ContextValidationError: If conversation is missing or too short.
        """
        if ctx.conversation is None:
            msg = "conversation is required for ContradictionCheck"
            raise ContextValidationError(msg)
        if len(ctx.conversation) < 2:
            msg = "conversation must have at least 2 turns"
            raise ContextValidationError(msg)

    def evaluate(self, ctx: Context) -> CheckResult:
        """Evaluate for contradictions in conversation.

        Args:
            ctx: Context with conversation history to evaluate.

        Returns:
            CheckResult with contradiction score.
        """
        self.validate_context(ctx)
        assert ctx.conversation is not None

        # Build conversation string
        conv_lines = []
        for msg in ctx.conversation:
            role = msg.get("role", "unknown")
            content = msg.get("content", "")
            conv_lines.append(f"{role}: {content}")

        conversation_str = "\n".join(conv_lines)

        provider = get_provider()
        prompt = (
            f"CONVERSATION:\n{conversation_str}\n\n"
            f"Evaluate for self-contradictions and inconsistencies."
        )

        resp = provider.judge(system=JUDGE_PROMPT, user=prompt)

        return CheckResult(
            name=self.name,
            score=resp.get("score", 0.5),
            passed=resp.get("score", 0.5) >= self.threshold,
            threshold=self.threshold,
            evidence=resp.get("evidence", ""),
            cost_usd=resp.get("cost_usd", 0.0),
            tokens_used=resp.get("tokens", {}),
            check_version=self.version,
        )
