"""
Modèles pour l'interprétation automatique des messages ENT.
"""
from datetime import datetime, timezone
from app_new.extensions import db


class EntContext(db.Model):
    """Contexte pour l'interprétation automatique des messages ENT."""
    __tablename__ = "ent_context"
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    
    # Configuration de l'interprétation
    auto_interpret_enabled = db.Column(db.Boolean, default=False)
    auto_interpret_interval = db.Column(db.Integer, default=10)  # minutes
    auto_interpret_max_emails = db.Column(db.Integer, default=5)
    auto_interpret_lookback_hours = db.Column(db.Integer, default=24)
    
    # Contexte pour Hermes
    context_text = db.Column(db.Text, nullable=True)
    
    # Exclusions
    excluded_senders = db.Column(db.Text, nullable=True)  # JSON list
    
    # Timestamps
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
    
    def __repr__(self):
        return f"<EntContext user={self.user_id}>"


class EntMessageInterpretation(db.Model):
    """Interprétation automatique d'un message ENT par Hermes."""
    __tablename__ = "ent_message_interpretations"
    
    id = db.Column(db.Integer, primary_key=True)
    message_id = db.Column(db.String(100), db.ForeignKey("ent_messages.id"), nullable=False)
    
    # Résultat de l'analyse
    analysis_type = db.Column(db.String(50), nullable=True)  # curative, preventive, administrative, etc.
    analysis_priority = db.Column(db.String(20), nullable=True)  # low, medium, high, critical
    analysis_summary = db.Column(db.Text, nullable=True)
    analysis_action = db.Column(db.String(50), default="create")  # create, ignore, forward
    analysis_confidence = db.Column(db.Float, default=0.0)
    
    # Données structurées
    suggested_location_id = db.Column(db.Integer, db.ForeignKey("rooms.id"), nullable=True)
    suggested_equipment = db.Column(db.String(200), nullable=True)
    suggested_description = db.Column(db.Text, nullable=True)
    
    # Interventions créées
    interventions_created = db.Column(db.Integer, default=0)
    
    # Statut
    status = db.Column(db.String(20), default="pending")  # pending, accepted, rejected
    
    # Timestamps
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    processed_at = db.Column(db.DateTime, nullable=True)
    
    # Relations
    message = db.relationship("EntMessage", backref="interpretation", uselist=False)
    
    def __repr__(self):
        return f"<EntMessageInterpretation {self.message_id}>"