"""Autonomous self-QA contracts for agent result verification."""

from __future__ import annotations

from dataclasses import asdict, dataclass, field
from typing import Any

from pydantic import BaseModel, Field


@dataclass
class SelfQAAssertion:
    """Single check the answer must satisfy."""

    assertion: str
    rationale: str | None = None


@dataclass
class SelfQACheck:
    """Verification outcome for one assertion."""

    assertion: str
    passed: bool
    evidence: str | None = None
    failure_reason: str | None = None


@dataclass
class SelfQAVerdict:
    """Tester verdict over a candidate answer."""

    passed: bool
    summary: str
    checks: list[SelfQACheck] = field(default_factory=list)


@dataclass
class SelfQAAttempt:
    """Single self-QA attempt with candidate, assertions, and verdict."""

    attempt: int
    candidate: str
    assertions: list[SelfQAAssertion] = field(default_factory=list)
    verdict: SelfQAVerdict | None = None
    revised_candidate: str | None = None


@dataclass
class SelfQAReport:
    """Final self-QA report attached to the agent response."""

    passed: bool
    attempts: list[SelfQAAttempt] = field(default_factory=list)
    final_summary: str = ""
    max_retries: int = 0

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)


class SelfQAAssertionModel(BaseModel):
    """Structured schema for generated assertions."""

    assertion: str = Field(min_length=1)
    rationale: str | None = None


class SelfQAPlanModel(BaseModel):
    """Structured schema for the assertion plan."""

    assertions: list[SelfQAAssertionModel] = Field(min_length=1, max_length=3)


class SelfQACheckModel(BaseModel):
    """Structured schema for a single verification check."""

    assertion: str = Field(min_length=1)
    passed: bool
    evidence: str | None = None
    failure_reason: str | None = None


class SelfQAVerdictModel(BaseModel):
    """Structured schema for the full tester verdict."""

    passed: bool
    summary: str = Field(min_length=1)
    checks: list[SelfQACheckModel] = Field(min_length=1)
