"""
Environmental Insight model for Context Learning system.

This model stores generated insights about client/infrastructure environments,
helping Claude learn from failures and provide better suggestions over time.
"""

from datetime import datetime
from typing import Optional

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

from .base import Base, TimestampMixin, UUIDMixin


class EnvironmentalInsight(Base, UUIDMixin, TimestampMixin):
    """
    Environmental insights for client/infrastructure environments.

    Stores learned insights about environmental constraints, configurations,
    and best practices discovered through failure analysis and verification.
    Used to generate insights.md files and provide context-aware suggestions.

    Attributes:
        id: Unique identifier
        client_id: Reference to the client this insight applies to
        infrastructure_id: Reference to specific infrastructure if applicable
        insight_category: Category of insight (command_constraints, service_configuration, etc.)
        insight_title: Brief title describing the insight
        insight_description: Detailed markdown-formatted description
        examples: JSON array of command/configuration examples
        source_pattern_id: Reference to failure pattern that generated this insight
        confidence_level: How confident we are (confirmed, likely, suspected)
        verification_count: Number of times this insight has been verified
        priority: Priority level (1-10, higher = more important)
        last_verified: When this insight was last verified
        created_at: When the insight was created
        updated_at: When the insight was last updated
    """

    __tablename__ = "environmental_insights"

    # Foreign keys
    client_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("clients.id", ondelete="CASCADE"),
        nullable=True,
        doc="Client this insight applies to",
    )
    infrastructure_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("infrastructure.id", ondelete="CASCADE"),
        nullable=True,
        doc="Specific infrastructure if applicable",
    )

    # Insight content
    insight_category: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
        doc="Category of insight",
    )
    insight_title: Mapped[str] = mapped_column(
        String(500),
        nullable=False,
        doc="Brief title describing the insight",
    )
    insight_description: Mapped[str] = mapped_column(
        Text,
        nullable=False,
        doc="Detailed markdown-formatted description",
    )
    examples: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        doc="JSON array of command/configuration examples",
    )

    # Metadata
    source_pattern_id: Mapped[Optional[str]] = mapped_column(
        CHAR(36),
        ForeignKey("failure_patterns.id", ondelete="SET NULL"),
        nullable=True,
        doc="Failure pattern that generated this insight",
    )
    confidence_level: Mapped[Optional[str]] = mapped_column(
        String(20),
        nullable=True,
        doc="Confidence level in this insight",
    )
    verification_count: Mapped[int] = mapped_column(
        Integer,
        default=1,
        server_default="1",
        nullable=False,
        doc="Number of times verified",
    )
    priority: Mapped[int] = mapped_column(
        Integer,
        default=5,
        server_default="5",
        nullable=False,
        doc="Priority level (1-10, higher = more important)",
    )
    last_verified: Mapped[Optional[datetime]] = mapped_column(
        nullable=True,
        doc="When this insight was last verified",
    )

    # Indexes and constraints
    __table_args__ = (
        CheckConstraint(
            "insight_category IN ('command_constraints', 'service_configuration', 'version_limitations', 'custom_installations', 'network_constraints', 'permissions')",
            name="ck_insights_category",
        ),
        CheckConstraint(
            "confidence_level IN ('confirmed', 'likely', 'suspected')",
            name="ck_insights_confidence",
        ),
        Index("idx_insights_client", "client_id"),
        Index("idx_insights_infrastructure", "infrastructure_id"),
        Index("idx_insights_category", "insight_category"),
    )

    # Relationships
    # client = relationship("Client", back_populates="environmental_insights")
    # infrastructure = relationship("Infrastructure", back_populates="environmental_insights")
    # source_pattern = relationship("FailurePattern", back_populates="generated_insights")

    def __repr__(self) -> str:
        """String representation of the environmental insight."""
        return (
            f"<EnvironmentalInsight(id={self.id!r}, "
            f"category={self.insight_category!r}, "
            f"title={self.insight_title!r})>"
        )
