"""Replay-set contracts for risk graph algorithm evaluation."""

from __future__ import annotations

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


@dataclass(frozen=True, slots=True)
class AlgorithmReplayCase:
    replay_case_id: str
    claim_id: str
    ontology_version: str
    rule_version: str
    algorithm_version: str
    feedback_label: str
    payload: dict[str, Any] = field(default_factory=dict)

    def as_dict(self) -> dict[str, Any]:
        return {
            "replay_case_id": self.replay_case_id,
            "claim_id": self.claim_id,
            "ontology_version": self.ontology_version,
            "rule_version": self.rule_version,
            "algorithm_version": self.algorithm_version,
            "feedback_label": self.feedback_label,
            "payload": dict(self.payload),
        }


@dataclass(slots=True)
class AlgorithmReplaySet:
    replay_set_id: str
    created_at: datetime
    cases: list[AlgorithmReplayCase] = field(default_factory=list)

    def as_dict(self) -> dict[str, Any]:
        return {
            "replay_set_id": self.replay_set_id,
            "created_at": self.created_at.isoformat(),
            "case_count": len(self.cases),
            "cases": [item.as_dict() for item in self.cases],
        }


class AlgorithmReplaySetBuilder:
    def build_from_observations(
        self,
        replay_set_id: str,
        observations: list[dict[str, Any]],
        *,
        created_at: datetime,
    ) -> AlgorithmReplaySet:
        cases = [
            self._case_from_observation(index, observation)
            for index, observation in enumerate(observations, start=1)
        ]
        return AlgorithmReplaySet(
            replay_set_id=replay_set_id,
            created_at=created_at,
            cases=cases,
        )

    def _case_from_observation(
        self,
        index: int,
        observation: dict[str, Any],
    ) -> AlgorithmReplayCase:
        ontology = observation.get("ontology_json") or {}
        trace = observation.get("decision_trace") or {}
        return AlgorithmReplayCase(
            replay_case_id=str(
                observation.get("evaluation_case_id")
                or trace.get("evaluation_case_id")
                or f"replay:{index}:{observation.get('observation_key') or 'observation'}"
            ),
            claim_id=str(observation.get("claim_id") or ""),
            ontology_version=str(ontology.get("ontology_version") or ""),
            rule_version=str(trace.get("rule_version") or ""),
            algorithm_version=str(observation.get("algorithm_version") or ""),
            feedback_label=str(
                observation.get("feedback_status")
                or observation.get("status")
                or "unreviewed"
            ),
            payload={
                "risk_signal": observation.get("risk_signal"),
                "risk_score": observation.get("risk_score"),
                "risk_level": observation.get("risk_level"),
                "decision_trace": trace,
            },
        )
