"""
Distillation Domain Receipts

Receipt types for prophecy local distillation tracking.

Records all local model inference attempts, escalation decisions, and cost savings.
Provides audit trail for understanding where distillation succeeds vs. fails.

---
feature:
  id: feature.distillation_receipts
  name: Distillation Domain Receipts
  kind: module
  summary: Receipt models for prophecy distillation cost tracking
  owners: ["@agent-c"]
  stage: experimental
  tags: [receipts, distillation, prophecy, cost-optimization]
  depends_on: [feature.receipt_writer, feature.prophecy_distillation]
  inputs: [Distillation decisions, local predictions]
  outputs: [Signed distillation receipts in ledger]
  invariants:
    - All distillation receipts are Ed25519-signed
    - Cost savings are tracked per decision
    - Confidence and escalation decisions are auditable
---
"""

from __future__ import annotations

import logging
from typing import Any, Dict, Optional

from pydantic import Field

from receipts.base import BaseReceipt

logger = logging.getLogger(__name__)


class DistillationReceipt(BaseReceipt):
    """
    Emitted when a prophecy prediction is attempted locally.

    Records the local model inference, confidence, and escalation decision.
    Provides audit trail for cost savings and model performance.

    Fields:
        local_model: Which local model was used (smollm:360m, llama3.2:3b)
        confidence: Calibrated confidence score (0.0-1.0)
        raw_confidence: Uncalibrated model confidence (0.0-1.0)
        escalated: Was this escalated to API? (True/False)
        inference_time_ms: How long local inference took (milliseconds)
        api_cost_saved: How much API cost was saved (USD, $0.01 or $0.00)
        task_context: Task context used for prediction
    """

    receipt_type: str = Field(default="DistillationReceipt", alias="type")
    domain: str = Field(default="organism")

    # Model identity
    local_model: str = Field(description="Local model used: smollm:360m, llama3.2:3b, etc.")

    # Confidence
    confidence: float = Field(description="Calibrated confidence score (0.0-1.0)")
    raw_confidence: float = Field(description="Uncalibrated model confidence (0.0-1.0)")

    # Decision
    escalated: bool = Field(description="Was this prediction escalated to API?")

    # Performance
    inference_time_ms: float = Field(description="Local inference time in milliseconds")

    # Cost tracking
    api_cost_saved: float = Field(description="API cost saved by using local model (USD)")

    # Context (for debugging)
    task_context: Dict[str, Any] = Field(description="Task context for this prediction")


class DistillationStatsReceipt(BaseReceipt):
    """
    Emitted periodically to track aggregate distillation performance.

    Provides high-level view of cost savings and model effectiveness.

    Fields:
        total_predictions: Total number of predictions attempted
        local_handled: How many were handled locally (no API escalation)
        quick_model_handled: How many quick model (smollm) handled
        refined_model_handled: How many refined model (llama3.2) handled
        escalated_count: How many escalated to API
        cost_savings_pct: Percentage cost savings vs. API-only (0.0-100.0)
        total_api_cost_saved: Total API cost saved (USD)
        avg_local_time_ms: Average local inference time (milliseconds)
    """

    receipt_type: str = Field(default="DistillationStatsReceipt", alias="type")
    domain: str = Field(default="organism")

    # Counts
    total_predictions: int = Field(description="Total predictions attempted")
    local_handled: int = Field(description="Predictions handled locally (no API)")
    quick_model_handled: int = Field(description="Handled by quick model (smollm)")
    refined_model_handled: int = Field(description="Handled by refined model (llama3.2)")
    escalated_count: int = Field(description="Escalated to API")

    # Cost savings
    cost_savings_pct: float = Field(description="Cost savings percentage (0.0-100.0)")
    total_api_cost_saved: float = Field(description="Total API cost saved (USD)")

    # Performance
    avg_local_time_ms: float = Field(description="Average local inference time (ms)")
    local_handle_rate: float = Field(description="Local handle rate (0.0-1.0)")


class CalibrationUpdateReceipt(BaseReceipt):
    """
    Emitted when calibration is updated based on actual outcomes.

    Records how we're adjusting confidence based on real-world performance.

    Fields:
        model: Which model's calibration was updated
        task_type: Task type for this calibration
        prediction_confidence: What the model predicted (0.0-1.0)
        actual_outcome: What actually happened (success/failure)
        calibration_adjustment: New confidence multiplier for this pattern
        sample_size: How many observations for this pattern
    """

    receipt_type: str = Field(default="CalibrationUpdateReceipt", alias="type")
    domain: str = Field(default="organism")

    # Model identity
    model: str = Field(description="Model being calibrated (smollm:360m, llama3.2:3b)")

    # Task context
    task_type: str = Field(description="Task type for this calibration")

    # Prediction vs. actual
    prediction_confidence: float = Field(description="Model's predicted confidence (0.0-1.0)")
    actual_outcome: str = Field(description="Actual outcome: success or failure")

    # Calibration result
    calibration_adjustment: float = Field(description="Confidence multiplier adjustment")
    sample_size: int = Field(description="Number of observations for this pattern")

    # Accuracy metrics
    historical_accuracy: float = Field(description="Historical accuracy for this pattern (0.0-1.0)")
