# loom/receipts/command_intent_receipt.py

from __future__ import annotations

from datetime import datetime, timezone
from typing import Optional, List, TYPE_CHECKING
from dataclasses import dataclass, asdict, field
import json
import uuid

if TYPE_CHECKING:
    from loom.observers.voice.intent_parser import VoiceIntent
    from loom.guardian.voice_policies import VoiceGuardianVerdict

from receipts.evidence_receipt import EvidenceReceipt


@dataclass
class CommandIntentReceipt:
    """
    Receipt capturing a single parsed voice command and its Guardian verdict.

    This is DRY-RUN ONLY in Move 1: no effector execution yet.
    """

    type: str = "CommandIntentReceipt"
    receipt_id: str = ""
    created_at: str = ""

    # Who / what heard this (e.g., voice daemon ID)
    observer_id: str = "VoiceObserver"

    # Raw transcript
    raw_text: str = ""

    # Parsed intent
    intent_type: str = ""
    target: Optional[str] = None
    parameters: dict = field(default_factory=dict)

    # Guardian verdict
    guardian_allowed: bool = False
    guardian_risk_level: str = ""
    guardian_requires_confirmation: bool = False
    guardian_reasons: List[str] = field(default_factory=list)

    # For Move 1, no effector result yet
    execution_mode: str = "dry_run"

    # Multimodal evidence (optional in Move 1, mandatory for sensitive actions later)
    voice_evidence: Optional[EvidenceReceipt] = None
    vision_evidence: Optional[EvidenceReceipt] = None
    evidence_complete: bool = False
    guardian_decision: Optional[str] = None


# --- Helper to build receipts ------------------------------------------------

def build_command_intent_receipt(
    intent: "VoiceIntent",
    verdict: "VoiceGuardianVerdict",
    observer_id: str = "VoiceObserver",
) -> CommandIntentReceipt:
    now = datetime.now(timezone.utc)
    rid = f"cmd_{now.timestamp():.3f}_{uuid.uuid4().hex[:8]}"

    return CommandIntentReceipt(
        receipt_id=rid,
        created_at=now.isoformat(),
        observer_id=observer_id,
        raw_text=intent.raw_text,
        intent_type=intent.intent_type.value,
        target=intent.target,
        parameters=intent.parameters or {},
        guardian_allowed=verdict.allowed,
        guardian_risk_level=verdict.risk_level.value,
        guardian_requires_confirmation=verdict.requires_confirmation,
        guardian_reasons=verdict.reasons,
    )


def receipt_to_json(receipt: CommandIntentReceipt) -> str:
    """Convert receipt to JSON string"""
    return json.dumps(asdict(receipt))
