"""
Shell Scaffold State - Data models for shell state and command history

Defines ShellState and CommandEntry for persistent shell session management.
"""

from typing import Optional, List, Dict, Set
from datetime import datetime
from pydantic import Field

from egregore.core.context_scaffolds.data_types import ScaffoldState
from egregore.core.context_management.pact.components.core import XMLComponent


class CommandEntry(XMLComponent):
    """
    Single command execution record as XMLComponent.

    Stores complete information about a command execution including input,
    output, errors, exit code, and execution context.
    """
    type: str = "command"
    input: str = ""                                # Command that was executed
    output: str = ""                               # stdout content
    error: str = ""                                # stderr content
    exit_code: int = 0                             # Command exit status
    working_directory: str = ""                    # Directory when command was executed
    timestamp: str = Field(default_factory=lambda: datetime.now().isoformat())
    operation_type: str = "execute"                # For XML rendering


class ShellState(ScaffoldState):
    """
    Shell scaffold persistent state with change tracking.

    Maintains command history, active command, working directory, security configuration,
    and all shell session state with automatic change tracking for reactive updates.

    Note: command_history and blocked_commands are automatically wrapped with
    ChangeTrackingList and ChangeTrackingSet by ScaffoldState's _wrap_existing_fields().
    """
    # Command history and active state
    command_history: List[CommandEntry] = Field(default_factory=list)
    active_command: Optional[CommandEntry] = None   # Most recent command

    # Working directory (dual properties for compatibility)
    current_directory: str = ""                     # Current working directory (scaffold state)
    cwd: str = ""                                   # Current working directory (alias for cross-scaffold compatibility)

    # Session management
    session_id: str = ""                            # Unique session identifier
    shell_executable: str = "/bin/bash"             # Current shell being used
    blocked_commands: Set[str] = Field(default_factory=set)

    # Platform detection (set at initialization)
    is_windows: bool = False                        # True if running on Windows
    is_posix: bool = True                           # True if running on POSIX (Linux/macOS)
    platform_name: str = "posix"                   # os.name value ('nt', 'posix', etc.)

    # Security and approval system
    security_config: dict = Field(default_factory=dict)        # Resolved security configuration
    remembered_approvals: dict = Field(default_factory=dict)   # Policy learning: {command: [directories]}
    safe_directories: List[str] = Field(default_factory=list)  # Directories where dangerous commands auto-approve

    # Configuration stored in state (not instance attributes)
    viewport_end: int = -1                          # -1 = most recent history
    viewport_size: int = 8                          # Commands in history section
    max_output_tokens: int = 800                    # Per-command output limit
    command_timeout: int = 30                       # Default command timeout
    rm_to_mv: bool = True                           # Convert rm commands to mv for file recovery
    recovery_dir: str = ".temp"                     # Directory for recovered files
