# models.py — Response types for the COS SDK.
#
# These dataclasses mirror the server's ValidationResponse schema.
# Using dataclasses instead of Pydantic so the SDK has zero heavy dependencies.

from dataclasses import dataclass, field
from typing import List, Optional


@dataclass
class FlaggedClaim:
    """A single claim that COS flagged as potentially unreliable."""
    claim: str
    reason: str
    severity: str  # "low", "medium", or "high"
    correction: Optional[str] = None


@dataclass
class ModelVerdict:
    """One model's independent validation result (Tier 3 only)."""
    model_name: str
    confidence_score: float
    risk_level: str
    flagged_claims: List[FlaggedClaim] = field(default_factory=list)
    summary: str = ""


@dataclass
class ValidationResult:
    """The result of validating AI-generated text with COS.

    Attributes:
        confidence_score: 0.0 (definitely hallucinated) to 1.0 (fully reliable)
        risk_level: "low", "medium", or "high"
        flagged_claims: List of claims that COS found suspicious
        tier_used: Which validation tier was used ("tier_1", "tier_2", "tier_3")
        summary: Plain English explanation of the result
        verdicts: Individual model results (Tier 3 only, None for Tier 1/2)
    """
    confidence_score: float
    risk_level: str
    flagged_claims: List[FlaggedClaim] = field(default_factory=list)
    tier_used: str = "tier_1"
    summary: str = ""
    verdicts: Optional[List[ModelVerdict]] = None

    @classmethod
    def from_dict(cls, data: dict) -> "ValidationResult":
        """Parse a ValidationResult from the API JSON response."""
        flagged = [
            FlaggedClaim(
                claim=c.get("claim", ""),
                reason=c.get("reason", ""),
                severity=c.get("severity", "medium"),
                correction=c.get("correction"),
            )
            for c in data.get("flagged_claims", [])
        ]

        verdicts = None
        if data.get("verdicts"):
            verdicts = [
                ModelVerdict(
                    model_name=v.get("model_name", ""),
                    confidence_score=v.get("confidence_score", 0.0),
                    risk_level=v.get("risk_level", "medium"),
                    flagged_claims=[
                        FlaggedClaim(
                            claim=c.get("claim", ""),
                            reason=c.get("reason", ""),
                            severity=c.get("severity", "medium"),
                            correction=c.get("correction"),
                        )
                        for c in v.get("flagged_claims", [])
                    ],
                    summary=v.get("summary", ""),
                )
                for v in data["verdicts"]
            ]

        return cls(
            confidence_score=data.get("confidence_score", 0.0),
            risk_level=data.get("risk_level", "medium"),
            flagged_claims=flagged,
            tier_used=data.get("tier_used", "tier_1"),
            summary=data.get("summary", ""),
            verdicts=verdicts,
        )


@dataclass
class StreamEvent:
    """A single event from the SSE validation stream.

    Attributes:
        event: Event type — "t1_result", "validation_complete", "error", or "done"
        data: The event payload (ValidationResult for results, dict for errors)
    """
    event: str
    data: dict = field(default_factory=dict)

    @property
    def result(self) -> Optional[ValidationResult]:
        """Parse the event data as a ValidationResult (for t1_result and validation_complete)."""
        if self.event in ("t1_result", "validation_complete"):
            return ValidationResult.from_dict(self.data)
        return None
