from __future__ import annotations

from datetime import datetime
from typing import Any, Dict, List, Optional

from receipts.base import BaseReceipt
from receipts.compat.pyd import Field


class SigilExecutionReceipt(BaseReceipt):
    """Receipt emitted whenever a SIGIL script executes."""

    receipt_type: str = "SigilExecutionReceipt"
    domain: str = "sigil"

    sigil_source: str = Field(description="Raw SIGIL expression that executed.")
    glyphs: List[str] = Field(default_factory=list, description="Glyph sequence executed.")
    glyph_hash: str = Field(description="SHA-256 hash of the SIGIL script.")
    outcome: str = Field(description="success | failure | refusal.")
    context_frame_id: Optional[str] = Field(default=None, description="ContextFrame id, if any.")
    guardian_status: Optional[str] = Field(default=None, description="Status returned by Guardian glyph.")
    latency_ms: float = Field(description="Wall-clock latency for execution.")
    final_output: Optional[str] = Field(default=None, description="Final textual output (if any).")
    dip_profile: Dict[str, Any] = Field(
        default_factory=dict, description="Deterministic execution profile (hardware, libs, config)."
    )
    replay_seed: int = Field(default=0, description="Random seed used for deterministic replay.")
    replay_count: int = Field(default=1, description="Number of deterministic replays verified.")
    guardian_policy_hash: Optional[str] = Field(default=None, description="Hash of guardian policy enforcing this run.")
    cbf_status: str = Field(default="unknown", description="Status of the Control-Barrier-Function layer.")
    cbf_violations: List[str] = Field(default_factory=list, description="List of CBF violations detected.")
    lineage: Dict[str, Any] = Field(default_factory=dict, description="Lineage metadata (parents, context frame, ancestors).")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional execution metadata.")


class ContextFrameReceipt(BaseReceipt):
    """Receipt emitted whenever a ContextFrame is compiled."""

    receipt_type: str = "ContextFrameReceipt"
    domain: str = "sigil"

    frame_id: str = Field(description="ContextFrame identifier.")
    sigil_source: str = Field(description="SIGIL expression compiled.")
    glyphs: List[str] = Field(default_factory=list, description="Glyphs referenced in the frame.")
    glyph_hash: str = Field(description="SHA-256 hash of the SIGIL expression.")
    outcome: str = Field(description="success | failure.")
    compiled_at: datetime = Field(description="UTC timestamp when compilation finished.")
    dip_profile: Dict[str, Any] = Field(
        default_factory=dict, description="Deterministic profile for compilation/runtime expectations."
    )
    lineage: Dict[str, Any] = Field(default_factory=dict, description="Lineage metadata for the ContextFrame.")
