"""
Failure pattern model for tracking recurring environmental and compatibility issues.

This model identifies and documents patterns of failures across systems and clients,
enabling proactive problem resolution and system insights.
"""

from datetime import datetime
from typing import Optional

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

from api.models.base import Base, TimestampMixin, UUIDMixin


class FailurePattern(UUIDMixin, TimestampMixin, Base):
    """
    Track recurring failure patterns and environmental limitations.

    Documents patterns of failures that occur due to compatibility issues,
    environmental limitations, or system-specific constraints. Used to build
    institutional knowledge and prevent repeated mistakes.

    Attributes:
        id: UUID primary key
        infrastructure_id: Reference to affected infrastructure
        client_id: Reference to affected client
        pattern_type: Type of failure pattern
        pattern_signature: Brief identifier for the pattern
        error_pattern: Regex or keywords to match this failure
        affected_systems: JSON array of affected systems
        triggering_commands: JSON array of command patterns that trigger this
        triggering_operations: JSON array of operation types that trigger this
        failure_description: Detailed description of the failure
        root_cause: Why this failure occurs
        recommended_solution: The recommended approach to avoid/fix this
        alternative_approaches: JSON array of alternative solutions
        occurrence_count: How many times this pattern has been observed
        first_seen: When this pattern was first observed
        last_seen: When this pattern was last observed
        severity: Impact level (blocking, major, minor, info)
        is_active: Whether this pattern is still relevant
        added_to_insights: Whether this has been added to insights.md
        created_at: Creation timestamp
        updated_at: Last update timestamp
    """

    __tablename__ = "failure_patterns"

    # Foreign keys
    infrastructure_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("infrastructure.id", ondelete="CASCADE"),
        nullable=True,
        doc="Reference to affected infrastructure",
    )
    client_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("clients.id", ondelete="CASCADE"),
        nullable=True,
        doc="Reference to affected client",
    )

    # Pattern identification
    pattern_type: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
        doc="Type of failure pattern",
    )
    pattern_signature: Mapped[str] = mapped_column(
        String(500),
        nullable=False,
        doc="Brief identifier for the pattern (e.g., 'PowerShell 7 cmdlets on Server 2008')",
    )
    error_pattern: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="Regex or keywords to match this failure (e.g., 'Get-LocalUser.*not recognized')",
    )

    # Context
    affected_systems: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="JSON array of affected systems (e.g., ['all_server_2008', 'D2TESTNAS'])",
    )
    triggering_commands: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="JSON array of command patterns that trigger this failure",
    )
    triggering_operations: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="JSON array of operation types that trigger this failure",
    )

    # Resolution
    failure_description: Mapped[str] = mapped_column(
        Text,
        nullable=False,
        doc="Detailed description of the failure",
    )
    root_cause: Mapped[str] = mapped_column(
        Text,
        nullable=False,
        doc="Why this failure occurs (e.g., 'Server 2008 only has PowerShell 2.0')",
    )
    recommended_solution: Mapped[str] = mapped_column(
        Text,
        nullable=False,
        doc="The recommended approach to avoid/fix this (e.g., 'Use Get-WmiObject instead')",
    )
    alternative_approaches: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="JSON array of alternative solutions",
    )

    # Metadata
    occurrence_count: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        server_default="1",
        doc="How many times this pattern has been observed",
    )
    first_seen: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        doc="When this pattern was first observed",
    )
    last_seen: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        doc="When this pattern was last observed",
    )
    severity: Mapped[Optional[str]] = mapped_column(
        String(20),
        nullable=True,
        doc="Impact level",
    )
    is_active: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default="1",
        doc="Whether this pattern is still relevant",
    )
    added_to_insights: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default="0",
        doc="Whether this has been added to insights.md",
    )

    # Table constraints
    __table_args__ = (
        CheckConstraint(
            "pattern_type IN ('command_compatibility', 'version_mismatch', 'permission_denied', 'service_unavailable', 'configuration_error', 'environmental_limitation')",
            name="ck_failure_patterns_type",
        ),
        CheckConstraint(
            "severity IN ('blocking', 'major', 'minor', 'info')",
            name="ck_failure_patterns_severity",
        ),
        Index("idx_failure_infrastructure", "infrastructure_id"),
        Index("idx_failure_client", "client_id"),
        Index("idx_failure_pattern_type", "pattern_type"),
        Index("idx_failure_signature", "pattern_signature"),
    )

    def __repr__(self) -> str:
        """String representation of the failure pattern."""
        return f"<FailurePattern(id={self.id}, signature={self.pattern_signature}, severity={self.severity}, count={self.occurrence_count})>"
