"""
Extraction de salle/zone depuis le texte - GMAO College
Parse le corps des emails/messages pour identifier les salles mentionnees.
"""
import re
from ..extensions import db
from ..core.models.college import Room, Building


def extract_rooms_from_text(text):
    """Cherche des noms de salles dans le texte et retourne les Rooms correspondantes.
    
    Strategie :
    1. Chercher des patterns comme "salle B01", "B01", "couloir", "cour", etc.
    2. Fuzzy match avec les noms de salles en DB
    3. Retourne une liste de Room objects
    """
    if not text:
        return []
    
    text_lower = text.lower()
    rooms = Room.query.all()
    matched = []
    
    for room in rooms:
        if not room.name:
            continue
        room_name_lower = room.name.lower()
        # Match exact ou partiel
        if room_name_lower in text_lower:
            matched.append(room)
            continue
        # Match par code si la salle a un code
        if hasattr(room, 'code') and room.code:
            if room.code.lower() in text_lower:
                matched.append(room)
                continue
    
    # Dedoublonner
    seen_ids = set()
    unique = []
    for r in matched:
        if r.id not in seen_ids:
            unique.append(r)
            seen_ids.add(r.id)
    
    return unique


def extract_zone_from_text(text):
    """Cherche des zones mentionnees (cour, couloir, batiment A, etc.)."""
    if not text:
        return []
    
    text_lower = text.lower()
    buildings = Building.query.all()
    matched = []
    
    for b in buildings:
        if not b.name:
            continue
        if b.name.lower() in text_lower:
            matched.append(b)
    
    # Patterns communs
    common_zones = ['cour', 'couloir', 'gymnase', 'cantine', 'cdi', 'salle des professeurs', 
                    'chaufferie', 'garage', 'atelier', 'preau']
    for zone in common_zones:
        if zone in text_lower:
            matched.append(type('Zone', (), {'name': zone.capitalize(), 'id': None})())
    
    return matched


def enrich_interpretation_with_location(text, suggested_location=None, suggested_equipment=None):
    """Complete les informations de localisation manquantes depuis le texte.
    
    Si l'IA n'a pas trouve la salle, on cherche dans le texte.
    """
    result = {
        'rooms': [],
        'zones': [],
        'location': suggested_location or '',
    }
    
    # Si pas de location suggeree, chercher dans le texte
    if not suggested_location:
        rooms = extract_rooms_from_text(text)
        if rooms:
            result['rooms'] = [{'id': r.id, 'name': r.name} for r in rooms]
            result['location'] = rooms[0].name
    
    zones = extract_zone_from_text(text)
    if zones:
        result['zones'] = [z.name for z in zones]
        if not result['location']:
            result['location'] = zones[0].name
    
    return result