"""
Command run model for tracking shell/PowerShell/SQL commands executed.

This model records all commands executed during work sessions, including
success/failure status and enhanced failure tracking for diagnostics.
"""

from datetime import datetime
from typing import Optional

from sqlalchemy import CHAR, Boolean, ForeignKey, Index, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func

from api.models.base import Base, UUIDMixin


class CommandRun(UUIDMixin, Base):
    """
    Track commands executed during work sessions.

    Records shell, PowerShell, SQL, and other commands with execution details,
    output, and enhanced failure tracking for compatibility and environmental issues.

    Attributes:
        id: UUID primary key
        work_item_id: Reference to the work item
        session_id: Reference to the session
        command_text: The actual command that was executed
        host: Where the command was executed (hostname or IP)
        shell_type: Type of shell (bash, powershell, sql, docker, etc.)
        success: Whether the command succeeded
        output_summary: Summary of command output (first/last lines or error)
        exit_code: Command exit code (non-zero indicates failure)
        error_message: Full error text if command failed
        failure_category: Category of failure (compatibility, permission, syntax, environmental)
        resolution: How the failure was fixed (if resolved)
        resolved: Whether the failure has been resolved
        execution_order: Sequence number within work item
        created_at: When the command was executed
    """

    __tablename__ = "commands_run"

    # Foreign keys
    work_item_id: Mapped[str] = mapped_column(
        CHAR(36),
        ForeignKey("work_items.id", ondelete="CASCADE"),
        nullable=False,
        doc="Reference to work item",
    )
    session_id: Mapped[str] = mapped_column(
        CHAR(36),
        ForeignKey("sessions.id", ondelete="CASCADE"),
        nullable=False,
        doc="Reference to session",
    )

    # Command details
    command_text: Mapped[str] = mapped_column(
        Text,
        nullable=False,
        doc="The actual command that was executed",
    )
    host: Mapped[Optional[str]] = mapped_column(
        String(255),
        nullable=True,
        doc="Where the command was executed (hostname or IP)",
    )
    shell_type: Mapped[Optional[str]] = mapped_column(
        String(50),
        nullable=True,
        doc="Type of shell (bash, powershell, sql, docker, etc.)",
    )
    success: Mapped[Optional[bool]] = mapped_column(
        Boolean,
        nullable=True,
        doc="Whether the command succeeded",
    )
    output_summary: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="Summary of command output (first/last lines or error)",
    )

    # Failure tracking
    exit_code: Mapped[Optional[int]] = mapped_column(
        Integer,
        nullable=True,
        doc="Command exit code (non-zero indicates failure)",
    )
    error_message: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="Full error text if command failed",
    )
    failure_category: Mapped[Optional[str]] = mapped_column(
        String(100),
        nullable=True,
        doc="Category of failure (compatibility, permission, syntax, environmental)",
    )
    resolution: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="How the failure was fixed (if resolved)",
    )
    resolved: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default="0",
        doc="Whether the failure has been resolved",
    )

    # Execution metadata
    execution_order: Mapped[Optional[int]] = mapped_column(
        Integer,
        nullable=True,
        doc="Sequence number within work item",
    )

    # Timestamp
    created_at: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        doc="When the command was executed",
    )

    # Table constraints
    __table_args__ = (
        Index("idx_commands_work_item", "work_item_id"),
        Index("idx_commands_session", "session_id"),
        Index("idx_commands_host", "host"),
        Index("idx_commands_success", "success"),
        Index("idx_commands_failure_category", "failure_category"),
    )

    def __repr__(self) -> str:
        """String representation of the command run."""
        cmd_preview = self.command_text[:50] + "..." if len(self.command_text) > 50 else self.command_text
        return f"<CommandRun(id={self.id}, command={cmd_preview}, success={self.success})>"
