"""
AI Conversation History and Learning Models
Stores conversation history and learned patterns for self-training
"""

from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, Boolean, Numeric, JSON, Index
from sqlalchemy.orm import relationship
from datetime import datetime
from ...shared.config.database import Base


class AIConversation(Base):
    """Stores AI assistant conversation history"""
    __tablename__ = 'ai_conversations'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, index=True)
    session_id = Column(String(100), nullable=True, index=True)  # For grouping related conversations
    user_query = Column(Text, nullable=False)
    ai_response = Column(Text, nullable=False)
    intent = Column(String(100), nullable=True, index=True)
    context_used = Column(JSON, nullable=True)  # Store context data used
    user_role = Column(String(50), nullable=True, index=True)
    response_time_ms = Column(Integer, nullable=True)  # Response time in milliseconds
    is_helpful = Column(Boolean, nullable=True)  # User feedback on helpfulness
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True)
    
    # Relationships
    user = relationship('User', foreign_keys=[user_id])
    feedbacks = relationship('AIConversationFeedback', back_populates='conversation', cascade='all, delete-orphan')
    learned_patterns = relationship('AILearnedPattern', back_populates='source_conversation')
    
    __table_args__ = (
        Index('idx_ai_conv_user_date', 'user_id', 'created_at'),
        Index('idx_ai_conv_intent', 'intent'),
        Index('idx_ai_conv_session', 'session_id'),
    )


class AIConversationFeedback(Base):
    """User feedback on AI responses for learning"""
    __tablename__ = 'ai_conversation_feedbacks'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    conversation_id = Column(Integer, ForeignKey('ai_conversations.id'), nullable=False, index=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    rating = Column(Integer, nullable=True)  # 1-5 rating
    is_helpful = Column(Boolean, nullable=True)
    is_correct = Column(Boolean, nullable=True)
    feedback_text = Column(Text, nullable=True)  # User's text feedback
    correction = Column(Text, nullable=True)  # If user provides corrected answer
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    # Relationships
    conversation = relationship('AIConversation', back_populates='feedbacks')
    user = relationship('User', foreign_keys=[user_id])


class AILearnedPattern(Base):
    """Learned patterns from conversations for pattern matching"""
    __tablename__ = 'ai_learned_patterns'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    pattern_keywords = Column(Text, nullable=False)  # Keywords extracted from query
    query_pattern = Column(Text, nullable=False)  # Pattern template
    intent = Column(String(100), nullable=False, index=True)
    response_template = Column(Text, nullable=True)  # Response template
    context_keys = Column(JSON, nullable=True)  # Which context keys to use
    confidence_score = Column(Numeric(5, 2), nullable=False, default=0.0)  # Confidence 0-100
    usage_count = Column(Integer, nullable=False, default=0)  # How many times used
    success_count = Column(Integer, nullable=False, default=0)  # How many successful matches
    source_conversation_id = Column(Integer, ForeignKey('ai_conversations.id'), nullable=True)
    user_role = Column(String(50), nullable=True, index=True)  # Role-specific patterns
    is_active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    last_used_at = Column(DateTime, nullable=True)
    
    # Relationships
    source_conversation = relationship('AIConversation', back_populates='learned_patterns')
    
    __table_args__ = (
        Index('idx_ai_pattern_intent_role', 'intent', 'user_role'),
        Index('idx_ai_pattern_active', 'is_active', 'confidence_score'),
    )


class AIKnowledgeEntry(Base):
    """Dynamic knowledge base entries learned from interactions"""
    __tablename__ = 'ai_knowledge_entries'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    topic = Column(String(200), nullable=False, index=True)
    question = Column(Text, nullable=False)  # Common question format
    answer = Column(Text, nullable=False)  # Best answer
    keywords = Column(JSON, nullable=True)  # Keywords for matching
    related_intent = Column(String(100), nullable=True, index=True)
    source = Column(String(100), nullable=True)  # 'user_feedback', 'admin_added', 'learned'
    confidence = Column(Numeric(5, 2), nullable=False, default=50.0)  # 0-100
    usage_count = Column(Integer, nullable=False, default=0)
    success_count = Column(Integer, nullable=False, default=0)
    user_role = Column(String(50), nullable=True, index=True)  # Role-specific knowledge
    is_verified = Column(Boolean, nullable=False, default=False)  # Verified by admin
    created_by_user_id = Column(Integer, ForeignKey('users.id'), nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    last_used_at = Column(DateTime, nullable=True)
    
    # Relationships
    created_by = relationship('User', foreign_keys=[created_by_user_id])
    
    __table_args__ = (
        Index('idx_ai_knowledge_topic_role', 'topic', 'user_role'),
        Index('idx_ai_knowledge_active', 'is_verified', 'confidence'),
    )


class AITrainingMetrics(Base):
    """Metrics for tracking AI training and improvement"""
    __tablename__ = 'ai_training_metrics'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    metric_date = Column(DateTime, nullable=False, index=True)  # Date of metrics
    total_conversations = Column(Integer, nullable=False, default=0)
    total_patterns_learned = Column(Integer, nullable=False, default=0)
    total_knowledge_entries = Column(Integer, nullable=False, default=0)
    average_response_time_ms = Column(Integer, nullable=True)
    average_rating = Column(Numeric(3, 2), nullable=True)  # Average user rating
    helpful_rate = Column(Numeric(5, 2), nullable=True)  # Percentage of helpful responses
    correct_rate = Column(Numeric(5, 2), nullable=True)  # Percentage of correct responses
    pattern_match_success_rate = Column(Numeric(5, 2), nullable=True)
    knowledge_usage_rate = Column(Numeric(5, 2), nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    __table_args__ = (
        Index('idx_ai_metrics_date', 'metric_date'),
    )

