"""
Computer Use Models - Actions, Steps, and Receipts

Every screen action gets a cryptographic receipt for NatraLocke audit chain.
"""

import hashlib
from datetime import datetime
from enum import Enum
from typing import Optional, List, Tuple, Any
from pydantic import BaseModel, Field


class ActionType(str, Enum):
    """Types of actions the agent can take."""
    CLICK = "click"
    DOUBLE_CLICK = "double_click"
    RIGHT_CLICK = "right_click"
    TYPE = "type"
    PRESS = "press"           # Single key press
    HOTKEY = "hotkey"         # Key combination
    SCROLL = "scroll"
    MOVE = "move"
    DRAG = "drag"
    WAIT = "wait"
    SCREENSHOT = "screenshot"  # Just observe
    DONE = "done"             # Task complete
    FAILED = "failed"         # Cannot complete


class Action(BaseModel):
    """A single action to execute on screen."""
    action_type: ActionType
    x: Optional[int] = None
    y: Optional[int] = None
    text: Optional[str] = None
    key: Optional[str] = None
    keys: Optional[List[str]] = None
    scroll_amount: Optional[int] = None
    duration: Optional[float] = None
    reason: str = ""  # Why the model chose this action

    def to_command(self) -> str:
        """Human-readable command description."""
        if self.action_type == ActionType.CLICK:
            return f"click({self.x}, {self.y})"
        elif self.action_type == ActionType.DOUBLE_CLICK:
            return f"double_click({self.x}, {self.y})"
        elif self.action_type == ActionType.RIGHT_CLICK:
            return f"right_click({self.x}, {self.y})"
        elif self.action_type == ActionType.TYPE:
            return f"type('{self.text[:20]}...')" if len(self.text or "") > 20 else f"type('{self.text}')"
        elif self.action_type == ActionType.PRESS:
            return f"press('{self.key}')"
        elif self.action_type == ActionType.HOTKEY:
            return f"hotkey({', '.join(self.keys or [])})"
        elif self.action_type == ActionType.SCROLL:
            return f"scroll({self.scroll_amount})"
        elif self.action_type == ActionType.MOVE:
            return f"move({self.x}, {self.y})"
        elif self.action_type == ActionType.WAIT:
            return f"wait({self.duration}s)"
        elif self.action_type == ActionType.DONE:
            return "DONE"
        elif self.action_type == ActionType.FAILED:
            return f"FAILED: {self.reason}"
        return str(self.action_type.value)


class AgentStep(BaseModel):
    """A single step in the agent loop."""
    step_number: int
    timestamp: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
    screenshot_path: Optional[str] = None
    screenshot_hash: Optional[str] = None
    prompt_sent: str = ""
    model_response: str = ""
    action: Optional[Action] = None
    action_executed: bool = False
    execution_time_ms: float = 0.0
    vision_time_ms: float = 0.0


def _detect_remote_session() -> str:
    """Detect if running in a remote control session."""
    import os
    # Check for remote session indicators
    if os.environ.get("CLAUDE_REMOTE_SESSION"):
        return "remote_control"
    if os.environ.get("CLAUDE_SESSION_TYPE") == "remote":
        return "remote_control"
    return "local"


class ComputerUseReceipt(BaseModel):
    """
    NatraLocke-compatible receipt for computer use session.

    Every screen action gets a cryptographic audit trail.
    """
    schema_version: str = "computer_use_receipt_v1"
    session_id: str
    task_description: str
    started_at: str
    completed_at: Optional[str] = None

    # Provenance: where did this action originate?
    source: str = Field(default_factory=_detect_remote_session)  # "local" | "remote_control"

    steps: List[AgentStep] = Field(default_factory=list)

    # Outcome
    success: bool = False
    final_reason: str = ""
    total_actions: int = 0

    # Provenance
    model_name: str = ""
    screen_resolution: Tuple[int, int] = (0, 0)

    # Chain hash for NatraLocke
    receipt_hash: Optional[str] = None
    previous_receipt_hash: Optional[str] = None

    def compute_hash(self) -> str:
        """Compute SHA256 hash of receipt for audit chain."""
        content = f"{self.session_id}:{self.task_description}:{self.started_at}:{len(self.steps)}"
        for step in self.steps:
            if step.action:
                content += f":{step.action.to_command()}"
        return hashlib.sha256(content.encode()).hexdigest()[:32]

    def finalize(self, success: bool, reason: str = "") -> None:
        """Finalize receipt with outcome and hash."""
        self.completed_at = datetime.utcnow().isoformat()
        self.success = success
        self.final_reason = reason
        self.total_actions = sum(1 for s in self.steps if s.action_executed)
        self.receipt_hash = self.compute_hash()
