"""Insight Feedback database model for closed-loop learning."""

from sqlalchemy import Column, String, Boolean, DECIMAL, TIMESTAMP, Text, ForeignKey, Index
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import uuid

from app.core.database import Base


class InsightFeedback(Base):
    """Feedback tracking for AI Insights to enable learning."""

    __tablename__ = "insight_feedback"

    # Primary Key
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

    # Foreign Key to AIInsight
    insight_id = Column(
        UUID(as_uuid=True),
        ForeignKey('ai_insights.id', ondelete='CASCADE'),
        nullable=False,
        index=True
    )

    # Action Information
    action_taken = Column(
        String(100),
        comment="Specific action that was taken from recommendation_actions"
    )

    # Result Data
    result_data = Column(
        JSONB,
        comment="Detailed result data from applying the insight"
    )

    # Success Tracking
    success = Column(
        Boolean,
        nullable=False,
        index=True,
        comment="Whether the insight application was successful"
    )
    error_message = Column(
        Text,
        comment="Error message if success = false"
    )

    # Impact Comparison
    expected_impact_value = Column(
        DECIMAL(10, 2),
        comment="Expected impact value from original insight"
    )
    actual_impact_value = Column(
        DECIMAL(10, 2),
        comment="Measured actual impact after application"
    )
    variance_percentage = Column(
        DECIMAL(5, 2),
        comment="(actual - expected) / expected * 100"
    )

    # User Information
    applied_by = Column(
        String(100),
        comment="User or system that applied the insight"
    )

    # Timestamp
    created_at = Column(
        TIMESTAMP(timezone=True),
        server_default=func.now(),
        nullable=False,
        index=True
    )

    # Composite Indexes
    __table_args__ = (
        Index('idx_insight_success', 'insight_id', 'success'),
        Index('idx_created_success', 'created_at', 'success'),
    )

    def __repr__(self):
        return f"<InsightFeedback(id={self.id}, insight_id={self.insight_id}, success={self.success})>"
