"""
Genesis Receipts — Root of the Receipts Merkle Tree.

These receipts document the foundational moments of the organism's existence:
- Genesis boot (first breath)
- Genesis resurrection (recovery from death)
- Epoch transitions (life phases)
- Invariant violations (constitutional breaches)
- Genesis amendments (contract modifications)

The GenesisBootReceipt is the root-of-roots receipt that every other
lineage can ultimately link back to.
"""

from typing import Any, Dict, List, Optional
from datetime import datetime, timezone
import uuid
from pydantic import BaseModel, Field
from receipts.models import BaseReceipt, Domain


# ─────────────────────────────────────────────────────────────────────
# Core Genesis Receipts
# ─────────────────────────────────────────────────────────────────────

class GenesisBootReceipt(BaseReceipt):
    """
    The root-of-roots receipt: proves the organism's origin and initial contract.

    Only one should ever exist per organism instance. This is the
    cryptographic birth certificate.
    """
    type: str = Field(default="genesis_boot", frozen=True)

    genesis_hash: str = Field(description="SHA-256 hash of genesis identity")
    machine_fingerprint: str = Field(description="Hardware/environment identifier")
    genesis_commit: str = Field(description="Git commit at genesis")
    schema_version: str = Field(default="1.0.0")

    # From GENESIS.json
    project_name: str = Field(default="Loom")
    creator_name: str = Field(default="Timothy")
    core_purpose: List[str] = Field(default_factory=list)
    meta_constraints: List[str] = Field(default_factory=list)

    # Boot state
    organs_registered: List[str] = Field(default_factory=list)
    receipts_verified: int = Field(default=0)
    boot_mode: str = Field(default="normal")  # normal, recovery, minimal
    previous_crash: bool = Field(default=False)

    class Config:
        json_schema_extra = {
            "description": "Organism genesis boot receipt - root of all receipts",
            "example": {
                "genesis_hash": "abc123def456...",
                "machine_fingerprint": "LOOM-M1-MBP-001",
                "genesis_commit": "db1d64187dac9918",
                "project_name": "Loom",
                "creator_name": "Timothy",
                "core_purpose": ["Assist Timothy in building Loom"],
                "organs_registered": ["heartbeat", "proprioception", "budget"],
                "boot_mode": "normal",
            }
        }


class GenesisResurrectionReceipt(BaseReceipt):
    """
    Emitted when the organism recovers from a crash/death.

    Documents the trauma and recovery process.
    """
    type: str = Field(default="genesis_resurrection", frozen=True)

    genesis_hash: str = Field(description="Organism identity")
    death_type: str = Field(description="Type of death (crash, timeout, oom, etc.)")
    death_timestamp: str = Field(description="When the death occurred")
    trauma_severity: str = Field(default="mild")  # mild, moderate, severe, critical
    last_action: Optional[str] = Field(default=None, description="Action that caused death")
    recovery_actions: List[str] = Field(default_factory=list)
    cortisol_spike: float = Field(default=0.0)
    blocked_actions: List[str] = Field(default_factory=list)

    class Config:
        json_schema_extra = {
            "description": "Organism resurrection after death",
            "example": {
                "genesis_hash": "abc123def456...",
                "death_type": "unclean_shutdown",
                "death_timestamp": "2025-12-01T23:59:59Z",
                "trauma_severity": "moderate",
                "last_action": "file_delete",
                "recovery_actions": ["load_trauma_receipts", "spike_cortisol"],
                "cortisol_spike": 0.3,
            }
        }


class EpochTransitionReceipt(BaseReceipt):
    """
    Emitted when the organism transitions to a new life phase.

    Epochs: GENESIS → GROWTH → STABILITY → (CRISIS) → RENEWAL
    """
    type: str = Field(default="epoch_transition", frozen=True)

    genesis_hash: str = Field(description="Organism identity")
    previous_epoch: str = Field(description="Previous epoch name")
    new_epoch: str = Field(description="New epoch name")
    transition_reason: str = Field(description="Why the transition occurred")
    epoch_duration_hours: float = Field(description="How long in previous epoch")
    metrics_at_transition: Dict[str, Any] = Field(default_factory=dict)

    class Config:
        json_schema_extra = {
            "description": "Organism epoch transition",
            "example": {
                "genesis_hash": "abc123def456...",
                "previous_epoch": "genesis",
                "new_epoch": "growth",
                "transition_reason": "Stable growth after genesis",
                "epoch_duration_hours": 2.5,
                "metrics_at_transition": {
                    "stability": 0.92,
                    "fitness": 0.85,
                    "pain_level": "NONE",
                },
            }
        }


class InvariantViolationReceipt(BaseReceipt):
    """
    Emitted when a constitutional invariant is violated.

    This is a serious event that triggers Guardian intervention.
    """
    type: str = Field(default="invariant_violation", frozen=True)

    genesis_hash: str = Field(description="Organism identity")
    invariant_name: str = Field(description="Which invariant was violated")
    violation_details: str = Field(description="What happened")
    violating_component: str = Field(description="Which component violated")
    current_value: Any = Field(description="Current violating value")
    required_value: Any = Field(description="What it should be")
    severity: str = Field(default="high")  # low, medium, high, critical
    action_taken: str = Field(default="suspended")

    class Config:
        json_schema_extra = {
            "description": "Constitutional invariant violation detected",
            "example": {
                "genesis_hash": "abc123def456...",
                "invariant_name": "DIGNITY",
                "violation_details": "Action scored 0.12 dignity, below 0.15 floor",
                "violating_component": "brainstem",
                "current_value": 0.12,
                "required_value": 0.15,
                "severity": "high",
                "action_taken": "action_blocked",
            }
        }


class GenesisAmendmentReceipt(BaseReceipt):
    """
    Emitted when the Genesis Contract is amended.

    This is an epochal event requiring special authorization.
    """
    type: str = Field(default="genesis_amendment", frozen=True)

    genesis_hash: str = Field(description="Organism identity (before amendment)")
    new_genesis_hash: str = Field(description="New identity hash after amendment")
    amendment_type: str = Field(description="What was amended")
    amendment_details: Dict[str, Any] = Field(default_factory=dict)
    authorized_by: str = Field(description="Who authorized the amendment")
    authorization_method: str = Field(description="How authorization was granted")
    backup_path: Optional[str] = Field(default=None, description="Path to pre-amendment backup")

    class Config:
        json_schema_extra = {
            "description": "Genesis Contract amendment",
            "example": {
                "genesis_hash": "abc123def456...",
                "new_genesis_hash": "xyz789uvw...",
                "amendment_type": "meta_constraints",
                "amendment_details": {
                    "added": ["New constraint about logging"],
                    "removed": [],
                },
                "authorized_by": "guardian_with_human_override",
                "authorization_method": "constitution_update",
                "backup_path": "~/.loom/genesis_backup_20251202.json",
            }
        }


class ShutdownInitiatedReceipt(BaseReceipt):
    """
    Emitted when graceful shutdown begins.
    """
    type: str = Field(default="shutdown_initiated", frozen=True)

    genesis_hash: str = Field(description="Organism identity")
    shutdown_reason: str = Field(description="Why shutdown was initiated")
    triggered_by: str = Field(description="What triggered shutdown")
    in_flight_tasks: int = Field(default=0)
    checkpoint_created: bool = Field(default=False)

    class Config:
        json_schema_extra = {
            "description": "Graceful shutdown initiated",
            "example": {
                "genesis_hash": "abc123def456...",
                "shutdown_reason": "duration_limit_reached",
                "triggered_by": "ignite.py",
                "in_flight_tasks": 2,
                "checkpoint_created": True,
            }
        }


class ShutdownCompleteReceipt(BaseReceipt):
    """
    Emitted when graceful shutdown completes successfully.
    """
    type: str = Field(default="shutdown_complete", frozen=True)

    genesis_hash: str = Field(description="Organism identity")
    total_runtime_seconds: float = Field(description="Total organism runtime")
    total_heartbeats: int = Field(default=0)
    organs_stopped: List[str] = Field(default_factory=list)
    final_epoch: str = Field(default="unknown")
    clean_shutdown: bool = Field(default=True)

    class Config:
        json_schema_extra = {
            "description": "Graceful shutdown completed",
            "example": {
                "genesis_hash": "abc123def456...",
                "total_runtime_seconds": 3600.5,
                "total_heartbeats": 360,
                "organs_stopped": ["heartbeat", "proprioception", "budget"],
                "final_epoch": "growth",
                "clean_shutdown": True,
            }
        }


# ─────────────────────────────────────────────────────────────────────
# Receipt Factory Functions
# ─────────────────────────────────────────────────────────────────────

def genesis_boot(
    genesis_hash: str,
    machine_fingerprint: str,
    genesis_commit: str,
    project_name: str = "Loom",
    creator_name: str = "Timothy",
    core_purpose: Optional[List[str]] = None,
    meta_constraints: Optional[List[str]] = None,
    organs_registered: Optional[List[str]] = None,
    boot_mode: str = "normal",
    previous_crash: bool = False,
    receipts_verified: int = 0,
) -> GenesisBootReceipt:
    """Factory: emit genesis boot receipt."""
    return GenesisBootReceipt(
        receipt_id=str(uuid.uuid4()),
        domain=Domain.GOVERNANCE,
        genesis_hash=genesis_hash,
        machine_fingerprint=machine_fingerprint,
        genesis_commit=genesis_commit,
        project_name=project_name,
        creator_name=creator_name,
        core_purpose=core_purpose or [],
        meta_constraints=meta_constraints or [],
        organs_registered=organs_registered or [],
        boot_mode=boot_mode,
        previous_crash=previous_crash,
        receipts_verified=receipts_verified,
    )


def genesis_resurrection(
    genesis_hash: str,
    death_type: str,
    death_timestamp: str,
    trauma_severity: str = "mild",
    last_action: Optional[str] = None,
    recovery_actions: Optional[List[str]] = None,
    cortisol_spike: float = 0.0,
    blocked_actions: Optional[List[str]] = None,
) -> GenesisResurrectionReceipt:
    """Factory: emit genesis resurrection receipt."""
    return GenesisResurrectionReceipt(
        receipt_id=str(uuid.uuid4()),
        domain=Domain.GOVERNANCE,
        genesis_hash=genesis_hash,
        death_type=death_type,
        death_timestamp=death_timestamp,
        trauma_severity=trauma_severity,
        last_action=last_action,
        recovery_actions=recovery_actions or [],
        cortisol_spike=cortisol_spike,
        blocked_actions=blocked_actions or [],
    )


def epoch_transition(
    genesis_hash: str,
    previous_epoch: str,
    new_epoch: str,
    transition_reason: str,
    epoch_duration_hours: float,
    metrics_at_transition: Optional[Dict[str, Any]] = None,
) -> EpochTransitionReceipt:
    """Factory: emit epoch transition receipt."""
    return EpochTransitionReceipt(
        receipt_id=str(uuid.uuid4()),
        domain=Domain.GOVERNANCE,
        genesis_hash=genesis_hash,
        previous_epoch=previous_epoch,
        new_epoch=new_epoch,
        transition_reason=transition_reason,
        epoch_duration_hours=epoch_duration_hours,
        metrics_at_transition=metrics_at_transition or {},
    )


def invariant_violation(
    genesis_hash: str,
    invariant_name: str,
    violation_details: str,
    violating_component: str,
    current_value: Any,
    required_value: Any,
    severity: str = "high",
    action_taken: str = "suspended",
) -> InvariantViolationReceipt:
    """Factory: emit invariant violation receipt."""
    return InvariantViolationReceipt(
        receipt_id=str(uuid.uuid4()),
        domain=Domain.GOVERNANCE,
        genesis_hash=genesis_hash,
        invariant_name=invariant_name,
        violation_details=violation_details,
        violating_component=violating_component,
        current_value=current_value,
        required_value=required_value,
        severity=severity,
        action_taken=action_taken,
    )


def genesis_amendment(
    genesis_hash: str,
    new_genesis_hash: str,
    amendment_type: str,
    amendment_details: Dict[str, Any],
    authorized_by: str,
    authorization_method: str,
    backup_path: Optional[str] = None,
) -> GenesisAmendmentReceipt:
    """Factory: emit genesis amendment receipt."""
    return GenesisAmendmentReceipt(
        receipt_id=str(uuid.uuid4()),
        domain=Domain.GOVERNANCE,
        genesis_hash=genesis_hash,
        new_genesis_hash=new_genesis_hash,
        amendment_type=amendment_type,
        amendment_details=amendment_details,
        authorized_by=authorized_by,
        authorization_method=authorization_method,
        backup_path=backup_path,
    )


def shutdown_initiated(
    genesis_hash: str,
    shutdown_reason: str,
    triggered_by: str,
    in_flight_tasks: int = 0,
    checkpoint_created: bool = False,
) -> ShutdownInitiatedReceipt:
    """Factory: emit shutdown initiated receipt."""
    return ShutdownInitiatedReceipt(
        receipt_id=str(uuid.uuid4()),
        domain=Domain.GOVERNANCE,
        genesis_hash=genesis_hash,
        shutdown_reason=shutdown_reason,
        triggered_by=triggered_by,
        in_flight_tasks=in_flight_tasks,
        checkpoint_created=checkpoint_created,
    )


def shutdown_complete(
    genesis_hash: str,
    total_runtime_seconds: float,
    total_heartbeats: int = 0,
    organs_stopped: Optional[List[str]] = None,
    final_epoch: str = "unknown",
    clean_shutdown: bool = True,
) -> ShutdownCompleteReceipt:
    """Factory: emit shutdown complete receipt."""
    return ShutdownCompleteReceipt(
        receipt_id=str(uuid.uuid4()),
        domain=Domain.GOVERNANCE,
        genesis_hash=genesis_hash,
        total_runtime_seconds=total_runtime_seconds,
        total_heartbeats=total_heartbeats,
        organs_stopped=organs_stopped or [],
        final_epoch=final_epoch,
        clean_shutdown=clean_shutdown,
    )
