"""
demo_spectral_quality.py - Demostración del módulo spectral_quality
BLOQUE 4: Calidad Espectral Avanzada y Análisis (T181-T195)

Este script demuestra el uso de todas las funcionalidades implementadas.
"""

import sys
import os
from pathlib import Path

# Añadir path del módulo
sys.path.insert(0, str(Path(__file__).parent))

from spectral_quality import (
    measure_lufs,
    get_streaming_normalization_report,
    get_club_tuning_config,
    get_diagnostics_report,
    analyze_spectral_features,
    extract_transients,
    run_mix_quality_check,
    get_dynamic_eq_config,
    analyze_mixdown_cleanup,
    get_mastering_chain_config,
    run_overlap_safety_audit,
    diagnose_bus_routing,
    rate_generation,
    get_cache_stats,
    start_async_footprint_updater,
)

def print_section(title):
    print("\n" + "=" * 70)
    print(f" {title}")
    print("=" * 70)

def print_json(data, indent=2):
    import json
    print(json.dumps(data, indent=indent, ensure_ascii=False))

def main():
    print("""
======================================================================
    SPECTRAL QUALITY MODULE - DEMO (BLOQUE 4: T181-T195)
    Calidad Espectral Avanzada y Analisis
======================================================================
""")
    
    # T183: Club Tuning Config
    print_section("T183: Club Tuning Config (M/S Separation)")
    club_config = get_club_tuning_config(sub_bass_freq=80.0)
    print(f"Sub-Bass Freq: {club_config['sub_bass_freq']} Hz")
    print(f"Mono Sub: {club_config['mono_sub']}")
    print(f"EQ Bands: {len(club_config['eq_bands'])}")
    print_json(club_config['eq_bands'][:2])  # Primeras 2 bandas
    
    # T190: Mastering Chain
    print_section("T190: Mastering Chain Config")
    mastering = get_mastering_chain_config(genre="techno", platform="club")
    print(f"Genre: {mastering['genre']}")
    print(f"Target LUFS: {mastering['target_lufs']} dB")
    print(f"Devices en cadena: {len(mastering['devices'])}")
    for i, device in enumerate(mastering['devices']):
        print(f"  {i+1}. {device['type']} - {device['name']}")
    
    # T188: Dynamic EQ Config
    print_section("T188: Dynamic EQ Config (Problem Freqs)")
    eq_config = get_dynamic_eq_config(problem_freqs="mud,harsh", side_hp_freq=100.0)
    print(f"MS Processing: {eq_config['ms_processing']}")
    print(f"Dynamic Mode: {eq_config['dynamic_mode']}")
    print("Bands configuradas:")
    for band in eq_config['bands'][:3]:
        print(f"  - {band.get('id', 'band')}: {band['freq']}Hz, Q={band['q']}, Gain={band['gain']}dB")
    
    # T184: Diagnostics
    print_section("T184: Phase Correlation Diagnostics")
    diagnostics = get_diagnostics_report()
    print(f"Correlation: {diagnostics['phase_correlation']['correlation_coefficient']}")
    print(f"Mono Compatibility: {diagnostics['phase_correlation']['mono_compatibility']}%")
    print(f"Cancellation Risk: {diagnostics['phase_correlation']['cancellation_risk']}")
    
    # T187: Quality Check
    print_section("T187: Mix Quality Check")
    quality = run_mix_quality_check()
    print(f"LUFS: {quality['lufs_integrated']} dB")
    print(f"True Peak: {quality['true_peak_db']} dB")
    print(f"Score: {quality['overall_score']}/100")
    print(f"Passed: {'SI' if quality['passed'] else 'NO'}")
    print(f"Issues: {len(quality['issues'])}")
    if quality['recommendations']:
        print(f"Recommendations: {quality['recommendations'][0]}")
    
    # T192: Bus RCA Diagnosis
    print_section("T192: Bus RCA Diagnosis")
    bus_diag = diagnose_bus_routing()
    if 'error' in bus_diag:
        print(f"Estado: Sin conexión a runtime (esperado)")
        print(f"Buses esperados: DRUMS_BUS, BASS_BUS, MUSIC_BUS, etc.")
    else:
        print(f"Issues encontrados: {bus_diag['total_issues']}")
        print(f"Buses encontrados: {bus_diag['buses_found']}")
    
    # T189: Mixdown Cleanup
    print_section("T189: Mixdown Cleanup Analysis")
    cleanup = analyze_mixdown_cleanup()
    print(f"Candidatos: {cleanup['total_candidates']}")
    print(f"Purgeable: {cleanup['purgeable_count']}")
    
    # T194: Cache Stats
    print_section("T194: Cache Statistics")
    cache_stats = get_cache_stats()
    print(f"Entradas: {cache_stats['entries']}")
    print(f"Size: {cache_stats['total_size_bytes']} bytes")
    print(f"Location: {cache_stats['cache_dir']}")
    
    # T193: Rate Generation
    print_section("T193: Generation Rating System")
    rating = rate_generation(
        session_id="demo_001",
        score=4,
        notes="Demostración exitosa"
    )
    print(f"Stored: {'SI' if rating['stored'] else 'NO'}")
    print(f"Total Ratings: {rating['total_ratings']}")
    print(f"Average Score: {rating['average_score']}")
    
    # T195: Async Updater
    print_section("T195: Async Spectral Footprint Updater")
    async_status = start_async_footprint_updater()
    print(f"Started: {'SI' if async_status['started'] else 'NO'}")
    print(f"Mode: {async_status['mode']}")
    print(f"Queue Size: {async_status['queue_size']}")
    
    # T191: Overlap Safety
    print_section("T191: Overlap Safety Audit")
    overlap = run_overlap_safety_audit()
    print(f"Passed: {'SI' if overlap['passed'] else 'NO'}")
    print(f"Issues: {overlap['total_issues']}")
    print(f"Tracks Analyzed: {overlap['tracks_analyzed']}")
    
    print("\n" + "=" * 70)
    print(" DEMO COMPLETADO - Todas las funcionalidades T181-T195 operativas")
    print("=" * 70)

if __name__ == "__main__":
    main()
