"""
Feedback loop pour l'interpretation IA - GMAO College
Enregistre les corrections (suggestion IA vs realite) pour ameliorer l'IA.
"""
from datetime import datetime, timezone
from ..extensions import db


class InterpretationFeedback(db.Model):
    """Feedback sur une interpretation : compare la suggestion IA vs la realite."""
    __tablename__ = "interpretation_feedback"

    id = db.Column(db.Integer, primary_key=True)
    interpretation_id = db.Column(db.Integer, nullable=True)  # ID de l'interpretation
    source = db.Column(db.String(20), nullable=False)  # 'outlook' ou 'ent'
    
    # Suggestions IA
    ai_type = db.Column(db.String(50))
    ai_urgency = db.Column(db.String(20))
    ai_equipment = db.Column(db.String(200))
    ai_location = db.Column(db.String(200))
    
    # Corrections humaines (NULL = pas de correction = bonne suggestion)
    corrected_type = db.Column(db.String(50), nullable=True)
    corrected_urgency = db.Column(db.String(20), nullable=True)
    corrected_equipment = db.Column(db.String(200), nullable=True)
    corrected_location = db.Column(db.String(200), nullable=True)
    
    # Score
    was_correct = db.Column(db.Boolean, default=True)
    
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    
    def __repr__(self):
        return f"<InterpretationFeedback {self.source} correct={self.was_correct}>"


def record_feedback(interpretation_id, source, ai_suggestions, corrections=None):
    """Enregistre un feedback. Si corrections est None, la suggestion etait correcte."""
    fb = InterpretationFeedback(
        interpretation_id=interpretation_id,
        source=source,
        ai_type=ai_suggestions.get('type'),
        ai_urgency=ai_suggestions.get('urgency'),
        ai_equipment=ai_suggestions.get('equipment'),
        ai_location=ai_suggestions.get('location'),
    )
    
    if corrections:
        fb.corrected_type = corrections.get('type')
        fb.corrected_urgency = corrections.get('urgency')
        fb.corrected_equipment = corrections.get('equipment')
        fb.corrected_location = corrections.get('location')
        fb.was_correct = False
    else:
        fb.was_correct = True
    
    db.session.add(fb)
    db.session.commit()
    return fb


def get_feedback_stats():
    """Retourne des statistiques sur la precision de l'IA."""
    total = InterpretationFeedback.query.count()
    correct = InterpretationFeedback.query.filter_by(was_correct=True).count()
    incorrect = InterpretationFeedback.query.filter_by(was_correct=False).count()
    
    # Corrections par champ
    type_corrections = InterpretationFeedback.query.filter(
        InterpretationFeedback.corrected_type.isnot(None)
    ).count()
    equipment_corrections = InterpretationFeedback.query.filter(
        InterpretationFeedback.corrected_equipment.isnot(None)
    ).count()
    urgency_corrections = InterpretationFeedback.query.filter(
        InterpretationFeedback.corrected_urgency.isnot(None)
    ).count()
    
    accuracy = (correct / total * 100) if total > 0 else 0
    
    return {
        'total': total,
        'correct': correct,
        'incorrect': incorrect,
        'accuracy': round(accuracy, 1),
        'type_corrections': type_corrections,
        'equipment_corrections': equipment_corrections,
        'urgency_corrections': urgency_corrections,
    }