#!/usr/bin/env python3
"""
Traitement complet du séjour 15_23096332 avec sauvegarde en base
"""

from pathlib import Path
from pipeline_mco_pmsi.database.base import get_engine, get_session
from pipeline_mco_pmsi.database.models import StayDB, ClinicalDocumentDB
from pipeline_mco_pmsi.models.clinical import ClinicalDocument
from pipeline_mco_pmsi.models.metadata import StayMetadata
from pipeline_mco_pmsi.rag.rag_engine import RAGEngine
from pipeline_mco_pmsi.rag.referentiels_manager import ReferentielsManager
from pipeline_mco_pmsi.pipeline import Pipeline

print("=" * 60)
print("TRAITEMENT COMPLET DU SÉJOUR 15_23096332")
print("=" * 60)

# 1. Charger le séjour depuis la base
print("\n1️⃣  Chargement du séjour...")
engine = get_engine('sqlite:///pipeline_mco_pmsi.db')

with get_session(engine) as session:
    stay = session.query(StayDB).filter(StayDB.stay_id == '15_23096332').first()
    
    if not stay:
        print("❌ Séjour non trouvé")
        exit(1)
    
    print(f"✅ Séjour: {stay.stay_id}")
    
    # Récupérer les documents
    docs_db = session.query(ClinicalDocumentDB).filter(
        ClinicalDocumentDB.stay_id == stay.id
    ).order_by(ClinicalDocumentDB.priority).all()
    
    print(f"   Documents: {len(docs_db)}")
    
    # Convertir en modèles Pydantic
    documents = []
    for doc_db in docs_db:
        doc = ClinicalDocument(
            document_id=doc_db.document_id,
            document_type=doc_db.document_type,
            content=doc_db.content,
            creation_date=doc_db.creation_date,
            author=doc_db.author or 'Inconnu',
            priority=doc_db.priority
        )
        documents.append(doc)

# 2. Initialiser le RAG Engine
print("\n2️⃣  Initialisation du moteur RAG...")
referentiels_manager = ReferentielsManager(data_dir=Path('data/referentiels'))
rag_engine = RAGEngine(referentiels_manager=referentiels_manager)
print("✅ RAG Engine initialisé")

# 3. Créer le pipeline avec session DB
print("\n3️⃣  Traitement avec le pipeline complet...")
print("   ⏳ Cela peut prendre 3-5 minutes...")
print("   (extraction + codage + vérification + sauvegarde)")

with get_session(engine) as session:
    # Créer le pipeline
    pipeline = Pipeline(
        db_session=session,
        rag_engine=rag_engine
    )
    
    # Créer les métadonnées du séjour
    stay_metadata = StayMetadata(
        stay_id=stay.stay_id,
        admission_date=stay.admission_date,
        discharge_date=stay.discharge_date,
        specialty=stay.specialty
    )
    
    try:
        # Traiter le séjour (sauvegarde automatique en base)
        result = pipeline.process_stay(
            documents=documents,
            stay_metadata=stay_metadata
        )
        
        print("\n✅ Traitement terminé et sauvegardé en base !")
        
        print(f"\n📊 RÉSULTATS:")
        print(f"\n  DP: {result.coding_proposal.dp.code if result.coding_proposal.dp else 'Non proposé'}")
        if result.coding_proposal.dp:
            print(f"    {result.coding_proposal.dp.label}")
            print(f"    Confiance: {result.coding_proposal.dp.confidence:.2%}")
        
        print(f"\n  DR: {result.coding_proposal.dr.code if result.coding_proposal.dr else 'Non proposé'}")
        
        print(f"\n  DAS: {len(result.coding_proposal.das)} code(s)")
        for i, das in enumerate(result.coding_proposal.das[:3], 1):
            print(f"    {i}. {das.code} - {das.label}")
        
        print(f"\n  CCAM: {len(result.coding_proposal.ccam)} acte(s)")
        for i, ccam in enumerate(result.coding_proposal.ccam[:3], 1):
            print(f"    {i}. {ccam.code} - {ccam.label}")
        
        print(f"\n  Questions: {len(result.questions)}")
        print(f"  Problèmes de validation: {len(result.validation_issues)}")
        
        if result.verification_result:
            print(f"  Décision vérificateur: {result.verification_result.decision}")
        
        print(f"\n🌐 Interface web disponible sur: http://localhost:8001")
        print(f"   URL directe: http://localhost:8001/stays/15_23096332/coding-proposal")
        
    except Exception as e:
        print(f"\n❌ Erreur: {e}")
        import traceback
        traceback.print_exc()
        exit(1)

print("\n" + "=" * 60)
print("✅ TRAITEMENT TERMINÉ")
print("=" * 60)
