"""
Ground Truth Receipts - Audit trail for prediction evaluations.

Receipt types for the Ground Truth Guardian subsystem.
All receipts are Ed25519-signed, JCS-canonical, and stored in the standard
receipt ledger for unified audit trails.

---
feature:
  id: feature.ground_truth_receipts
  name: Ground Truth Domain Receipts
  kind: module
  summary: Receipt models for ground truth evaluation events
  owners: ["@codex"]
  stage: production
  tags: [receipts, guardian, learning, p0]
  depends_on: [feature.receipt_writer]
  inputs: [GroundTruthEvaluator events]
  outputs: [Signed receipts in ledger]
  invariants:
    - All receipts are Ed25519-signed
    - Every evaluation emits a receipt
    - Accuracy trends are monotonic (never decrease in count)
  risk_axes:
    unsigned_receipt: 0.0  # Enforced by writer
    missing_evaluation: 0.01
---
"""

from __future__ import annotations

import logging
from typing import Any, Optional

from pydantic import Field

from receipts.base import BaseReceipt

logger = logging.getLogger(__name__)


class GroundTruthEvaluationReceipt(BaseReceipt):
    """
    Emitted when a prediction is evaluated against ground truth.

    This receipt records the comparison between what was predicted
    and what actually happened, forming the basis of organism learning.
    """

    receipt_type: str = Field(default="GroundTruthEvaluationReceipt", alias="type")
    domain: str = Field(default="ground_truth")

    # Prediction identifiers
    prediction_id: str = Field(
        description="ID of the prediction being evaluated"
    )

    # Values
    predicted_value: Any = Field(
        description="What the organism predicted would happen"
    )
    actual_value: Any = Field(
        description="What actually happened"
    )

    # Evaluation results
    match: bool = Field(
        description="Whether prediction matched reality"
    )
    confidence_at_prediction: float = Field(
        ge=0.0,
        le=1.0,
        description="Organism's confidence when making prediction (0-1)"
    )
    error_magnitude: Optional[float] = Field(
        default=None,
        description="Absolute percentage error for numeric predictions"
    )

    # Metadata
    # domain field inherited from BaseReceipt is the prediction domain
    # (e.g., "stocks", "ncaab", "weather")


class GroundTruthStatsReceipt(BaseReceipt):
    """
    Emitted periodically with aggregate accuracy stats.

    Provides a snapshot of overall organism prediction accuracy,
    emitted every N evaluations to track learning over time.
    """

    receipt_type: str = Field(default="GroundTruthStatsReceipt", alias="type")
    domain: str = Field(default="ground_truth")

    # Aggregate statistics
    total_evaluations: int = Field(
        ge=0,
        description="Total number of predictions evaluated so far"
    )
    accuracy: float = Field(
        ge=0.0,
        le=1.0,
        description="Overall accuracy across all predictions (0-1)"
    )

    # Delta since last stats receipt
    evaluations_since_last: int = Field(
        ge=0,
        description="Number of evaluations since last stats receipt"
    )

    # Trend analysis
    accuracy_trend: str = Field(
        description="Trend direction: 'improving', 'declining', 'stable', or 'insufficient_data'"
    )
