"""
Vitality Receipt Domains

Receipt types for System Vitality tracking and constitutional control loop.

Note: These are standalone dataclasses, not inheriting from BaseReceipt,
to keep them simple and avoid Pydantic complexity.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Dict, List, Literal, Optional
import uuid


def _generate_receipt_id() -> str:
    """Generate a unique receipt ID."""
    return f"vitality-{uuid.uuid4().hex[:12]}"


def _now() -> datetime:
    """Get current UTC time."""
    return datetime.now(timezone.utc)


@dataclass
class VitalityTickReceipt:
    """
    Receipt for a single vitality tick from an organ.

    Emitted every 2-5 seconds per organ to track coherence and proof flow.
    """
    # Identity
    receipt_id: str = field(default_factory=_generate_receipt_id)
    receipt_type: str = "VitalityTickReceipt"
    ts: datetime = field(default_factory=_now)

    # Organ identity
    organ: str = ""                          # "Guardian", "Cortex", "Maestro"

    # Tri-metrics
    delta_c: float = 0.0                     # ΔC: coherence delta
    entropy_rate: float = 0.0                # H˙: uncertainty trend
    receipt_rate_per_min: float = 0.0        # R_rate: proof throughput

    # Computed
    vitality: float = 0.0                    # V = exp(-|ΔC|) × log(1 + R_rate)
    status: str = "green"                    # green | amber | red

    # Gate status
    gates: Dict[str, bool] = field(default_factory=dict)

    # PID state (optional, for debugging)
    pid_control_signal: Optional[float] = None
    pid_integral: Optional[float] = None


@dataclass
class ConstitutionalInterventionReceipt:
    """
    Receipt for a constitutional intervention.

    Emitted when the PID controller triggers a policy adjustment.
    """
    # Identity
    receipt_id: str = field(default_factory=_generate_receipt_id)
    receipt_type: str = "ConstitutionalInterventionReceipt"
    ts: datetime = field(default_factory=_now)

    # Context
    organ: str = ""
    trigger_delta_c: float = 0.0
    trigger_control_signal: float = 0.0

    # Intervention
    intervention_level: str = ""             # "pass" | "shadow_block" | "refuse"
    reason: str = ""

    # Policy adjustments applied
    adjustments: Dict[str, Any] = field(default_factory=dict)

    # Linked receipts
    triggering_tick_id: Optional[str] = None
    resulting_action_id: Optional[str] = None


@dataclass
class DignityFloorViolationReceipt:
    """
    Receipt for a dignity floor violation.

    Emitted when coherence drops below the constitutional floor.
    This is a critical receipt that triggers immediate intervention.
    """
    # Identity
    receipt_id: str = field(default_factory=_generate_receipt_id)
    receipt_type: str = "DignityFloorViolationReceipt"
    ts: datetime = field(default_factory=_now)

    # Context
    organ: str = ""
    coherence_at_violation: float = 0.0
    dignity_floor: float = 0.15              # Default floor

    # Violation details
    violation_type: str = ""                 # "below_floor" | "latched_degrade" | "gate_failure"
    severity: str = "critical"               # "warning" | "critical" | "emergency"

    # Action taken
    action: str = ""                         # "refuse" | "escalate" | "rollback"
    action_details: Dict[str, Any] = field(default_factory=dict)

    # Recovery
    recovery_required: bool = True
    recovery_path: Optional[str] = None


@dataclass
class EpochVitalitySummaryReceipt:
    """
    Receipt summarizing vitality across an epoch (60 seconds).

    Aggregates tick data for efficient storage and analysis.
    """
    # Identity
    receipt_id: str = field(default_factory=_generate_receipt_id)
    receipt_type: str = "EpochVitalitySummaryReceipt"
    ts: datetime = field(default_factory=_now)

    # Epoch identity
    epoch_id: str = ""
    epoch_start: Optional[datetime] = None
    epoch_end: Optional[datetime] = None

    # Per-organ summaries
    organ_summaries: Dict[str, Dict[str, Any]] = field(default_factory=dict)
    # e.g., {"Guardian": {"avg_delta_c": 0.1, "avg_vitality": 2.5, "status_counts": {"green": 10, "amber": 2}}}

    # Aggregate metrics
    total_ticks: int = 0
    total_receipts_issued: int = 0
    avg_system_vitality: float = 0.0
    worst_status: str = "green"

    # Interventions during epoch
    intervention_count: int = 0
    dignity_violations: int = 0


@dataclass
class ConstitutionalHandshakeReceipt:
    """
    Receipt for a constitutional handshake between organs.

    Used for Cortex → Maestro coordination with signed state continuity.
    """
    # Identity
    receipt_id: str = field(default_factory=_generate_receipt_id)
    receipt_type: str = "ConstitutionalHandshakeReceipt"
    ts: datetime = field(default_factory=_now)

    # Parties
    sender_organ: str = ""                   # e.g., "Cortex"
    receiver_organ: str = ""                 # e.g., "Maestro"

    # Intent
    intent: str = ""                         # "PLAN: triage tickets", "EXECUTE: assign owners"

    # State continuity
    context_hash: str = ""                   # SHA-256 of epistemic snapshot
    cycle_id: str = ""                       # "2025-12-04T12:00:00Z#1"
    prev_envelope_hash: Optional[str] = None # Links to prior cycle

    # Cryptographic proof
    nonce: str = ""
    pubkey: str = ""
    handshake_signature: str = ""            # Renamed to avoid shadowing

    # Verification (all have defaults)
    signature_valid: bool = False
    continuity_valid: bool = False
    accepted: bool = False


# Factory functions for easy receipt creation

def create_vitality_tick_receipt(
    organ: str,
    delta_c: float,
    entropy_rate: float,
    receipt_rate_per_min: float,
    vitality: float,
    status: str,
    gates: Dict[str, bool],
    pid_control_signal: Optional[float] = None,
) -> VitalityTickReceipt:
    """Create a vitality tick receipt."""
    return VitalityTickReceipt(
        organ=organ,
        delta_c=delta_c,
        entropy_rate=entropy_rate,
        receipt_rate_per_min=receipt_rate_per_min,
        vitality=vitality,
        status=status,
        gates=gates,
        pid_control_signal=pid_control_signal,
    )


def create_intervention_receipt(
    organ: str,
    delta_c: float,
    control_signal: float,
    intervention_level: str,
    reason: str,
    adjustments: Dict[str, Any],
) -> ConstitutionalInterventionReceipt:
    """Create a constitutional intervention receipt."""
    return ConstitutionalInterventionReceipt(
        organ=organ,
        trigger_delta_c=delta_c,
        trigger_control_signal=control_signal,
        intervention_level=intervention_level,
        reason=reason,
        adjustments=adjustments,
    )


def create_dignity_violation_receipt(
    organ: str,
    coherence: float,
    floor: float,
    violation_type: str,
    action: str,
) -> DignityFloorViolationReceipt:
    """Create a dignity floor violation receipt."""
    return DignityFloorViolationReceipt(
        organ=organ,
        coherence_at_violation=coherence,
        dignity_floor=floor,
        violation_type=violation_type,
        severity="critical",
        action=action,
        recovery_required=True,
    )


__all__ = [
    "VitalityTickReceipt",
    "ConstitutionalInterventionReceipt",
    "DignityFloorViolationReceipt",
    "EpochVitalitySummaryReceipt",
    "ConstitutionalHandshakeReceipt",
    "create_vitality_tick_receipt",
    "create_intervention_receipt",
    "create_dignity_violation_receipt",
]
