#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PROFESSIONAL_PRODUCTION.PY
Ejemplo completo de produccion profesional usando AbletonMCP_AI

Este script demuestra el flujo completo de produccion musical profesional
incluyendo: setup, produccion, FX, automation, mezcla y mastering.

Autor: AbletonMCP_AI Senior Architecture Team
Version: 3.0
Fecha: 2026-04-12

Instrucciones:
    1. Abrir Ableton Live 12 Suite
    2. Ejecutar health_check para verificar conexion
    3. Ejecutar este script o copiar comandos individuales
    
Requisitos:
    - Ableton Live 12 Suite
    - MCP Server configurado
    - Libreria de samples en carpeta 'libreria/'
"""

# =============================================================================
# SECCION 1: SETUP Y CONFIGURACION INICIAL
# =============================================================================

def setup_project():
    """
    Configuracion inicial del proyecto.
    SIEMPRE ejecutar primero para verificar sistema y configurar BPM.
    """
    print("""
    # PASO 1.1: Health Check Obligatorio
    # Verifica conectividad con Ableton Live - SIEMPRE ejecutar primero
    ableton-live-mcp_health_check
    
    # PASO 1.2: Configuracion del Proyecto
    # Configurar BPM para reggaeton (95 BPM es el estandar)
    ableton-live-mcp_set_tempo --tempo 95
    
    # Configurar firma de tiempo 4/4 (estandar para reggaeton)
    ableton-live-mcp_set_time_signature --numerator 4 --denominator 4
    
    # Activar metronomo (util durante la produccion)
    ableton-live-mcp_set_metronome --enabled true
    """)


# =============================================================================
# SECCION 2: CREACION DE ESTRUCTURA DE TRACKS
# =============================================================================

def create_track_structure():
    """
    Crea y organiza la estructura de tracks del proyecto.
    Organizacion recomendada:
        - Tracks 0-1: MIDI (reservados por Ableton)
        - Tracks 2-5: Audio (Drums: Kick, Snare, HiHat, Perc)
        - Tracks 6-8: MIDI (Bass, Chords, Melody)
        - Track 9: FX (Risers, Impacts, Transitions)
    """
    print("""
    # PASO 2.1: Crear Tracks de Audio (Drums)
    ableton-live-mcp_create_audio_track  # Track 2
    ableton-live-mcp_create_audio_track  # Track 3
    ableton-live-mcp_create_audio_track  # Track 4
    ableton-live-mcp_create_audio_track  # Track 5
    
    # PASO 2.2: Crear Tracks MIDI (Instrumentos)
    ableton-live-mcp_create_midi_track   # Track 6: Bass
    ableton-live-mcp_create_midi_track   # Track 7: Chords
    ableton-live-mcp_create_midi_track   # Track 8: Melody
    
    # PASO 2.3: Crear Tracks FX
    ableton-live-mcp_create_audio_track  # Track 9: FX
    
    # PASO 2.4: Nombrar Tracks
    ableton-live-mcp_set_track_name --track_index 2 --name "Kick"
    ableton-live-mcp_set_track_name --track_index 3 --name "Snare"
    ableton-live-mcp_set_track_name --track_index 4 --name "HiHat"
    ableton-live-mcp_set_track_name --track_index 5 --name "Percussion"
    ableton-live-mcp_set_track_name --track_index 6 --name "Bass"
    ableton-live-mcp_set_track_name --track_index 7 --name "Chords"
    ableton-live-mcp_set_track_name --track_index 8 --name "Melody"
    ableton-live-mcp_set_track_name --track_index 9 --name "FX"
    
    # PASO 2.5: Guardar Checkpoint
    ableton-live-mcp_save_checkpoint --name "setup_tracks_completo"
    """)


# =============================================================================
# SECCION 3: INYECCION DE SAMPLES EN ARRANGEMENT
# =============================================================================

def inject_samples():
    """
    Inyecta samples de audio directamente en Arrangement View.
    Este es el metodo SENIOR de produccion.
    
    Formato de posiciones:
        - 0 = Compas 1, Beat 1
        - 4 = Compas 2, Beat 1  
        - 8 = Compas 3, Beat 1
    """
    print("""
    # PASO 3.1: Pattern de Kick (16 compases)
    ableton-live-mcp_create_arrangement_audio_pattern \\
        --track_index 2 \\
        --file_path "C:\\...\\libreria\\reggaeton\\kick\\kick 1.wav" \\
        --positions [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60] \\
        --name "KickPattern"
    
    # PASO 3.2: Pattern de Snare (Backbeat)
    ableton-live-mcp_create_arrangement_audio_pattern \\
        --track_index 3 \\
        --file_path "C:\\...\\libreria\\reggaeton\\snare\\snare 1.wav" \\
        --positions [2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62] \\
        --name "SnarePattern"
    
    # PASO 3.3: Pattern de HiHat (8th notes)
    ableton-live-mcp_create_arrangement_audio_pattern \\
        --track_index 4 \\
        --file_path "C:\\...\\libreria\\reggaeton\\hi-hat\\hihat 1.wav" \\
        --positions [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31] \\
        --name "HiHatPattern"
    
    # PASO 3.4: Verificacion
    ableton-live-mcp_get_arrangement_status
    ableton-live-mcp_get_arrangement_clips
    """)


# =============================================================================
# SECCION 4: GENERACION MIDI (BASS, CHORDS, MELODY)
# =============================================================================

def generate_midi_content():
    """
    Genera contenido MIDI para completar la produccion.
    """
    print("""
    # PASO 4.1: Generar Linea de Bajo
    # Notas MIDI: 36=C2, 41=F2, 43=G2
    ableton-live-mcp_generate_bass_clip \\
        --track_index 6 \\
        --bars 16 \\
        --root_notes [36, 36, 41, 41, 43, 43, 36, 36] \\
        --style melodic
    
    # PASO 4.2: Generar Progresion de Acordes
    # i-v-vi-iv en Am (Am - Em - F - C)
    ableton-live-mcp_generate_chords_clip \\
        --track_index 7 \\
        --bars 16 \\
        --progression i-v-vi-iv \\
        --key Am
    
    # PASO 4.3: Generar Melodia
    ableton-live-mcp_generate_melody_clip \\
        --track_index 8 \\
        --bars 16 \\
        --scale minor \\
        --density medium
    
    # PASO 4.4: Humanizacion
    ableton-live-mcp_apply_human_feel --track_index 6 --intensity 0.3
    ableton-live-mcp_apply_human_feel --track_index 7 --intensity 0.2
    ableton-live-mcp_apply_human_feel --track_index 8 --intensity 0.4
    
    # PASO 4.5: Reproduccion
    ableton-live-mcp_start_playback
    """)


# =============================================================================
# SECCION 5: FX Y AUTOMATION
# =============================================================================

def add_fx_and_automation():
    """
    Añade efectos profesionales y automation.
    """
    print("""
    # PASO 5.1: Riser/Buildup (4 compases antes del chorus)
    ableton-live-mcp_create_riser \\
        --track_index 9 \\
        --start_bar 20 \\
        --duration 4 \\
        --intensity 0.8
    
    # PASO 5.2: Impact/Drop (en el chorus)
    ableton-live-mcp_create_impact \\
        --track_index 9 \\
        --position 24 \\
        --intensity 1.0 \\
        --impact_type sub_drop
    
    # PASO 5.3: Filter Sweep Automation
    ableton-live-mcp_automate_filter \\
        --track_index 7 \\
        --start_bar 20 \\
        --end_bar 24 \\
        --start_freq 200 \\
        --end_freq 20000
    
    # PASO 5.4: Percussion Fills
    ableton-live-mcp_add_percussion_fills \\
        --track_index 5 \\
        --positions [7, 15, 23, 31]
    
    # PASO 5.5: Downlifter
    ableton-live-mcp_create_downlifter \\
        --track_index 9 \\
        --start_bar 32 \\
        --duration 4 \\
        --intensity 0.7
    
    # PASO 5.6: Silence Effect
    ableton-live-mcp_create_silence \\
        --track_index 2 \\
        --start_bar 23 \\
        --duration 1
    """)


# =============================================================================
# SECCION 6: MEZCLA PROFESIONAL
# =============================================================================

def professional_mixing():
    """
    Aplica tecnicas profesionales de mezcla.
    """
    print("""
    # PASO 6.1: Crear Buses (Groups)
    ableton-live-mcp_create_bus_track --bus_type "Drums"
    ableton-live-mcp_route_track_to_bus --track_index 2 --bus_name "Drums"
    ableton-live-mcp_route_track_to_bus --track_index 3 --bus_name "Drums"
    ableton-live-mcp_route_track_to_bus --track_index 4 --bus_name "Drums"
    
    # PASO 6.2: Crear Pistas de Retorno
    ableton-live-mcp_create_return_track --effect_type "Reverb"
    ableton-live-mcp_create_return_track --effect_type "Delay"
    
    # PASO 6.3: Configurar Envios (Sends)
    ableton-live-mcp_set_track_send --track_index 8 --return_index 0 --amount 0.3
    ableton-live-mcp_set_track_send --track_index 7 --return_index 0 --amount 0.2
    
    # PASO 6.4: EQ
    ableton-live-mcp_configure_eq --track_index 2 --preset "kick"
    ableton-live-mcp_configure_eq --track_index 3 --preset "snare"
    ableton-live-mcp_configure_eq --track_index 6 --preset "bass"
    
    # PASO 6.5: Compresion
    ableton-live-mcp_configure_compressor \\
        --track_index 2 \\
        --preset "drums" \\
        --threshold -20 \\
        --ratio 4
    
    ableton-live-mcp_configure_compressor \\
        --track_index 6 \\
        --preset "bass" \\
        --threshold -15 \\
        --ratio 3
    
    # PASO 6.6: Sidechain Compression
    ableton-live-mcp_setup_sidechain \\
        --source_track 2 \\
        --target_track 6 \\
        --amount 0.7
    
    # PASO 6.7: Balance de Niveles
    ableton-live-mcp_auto_gain_staging
    ableton-live-mcp_set_track_volume --track_index 2 --volume 0.85
    ableton-live-mcp_set_track_volume --track_index 3 --volume 0.75
    ableton-live-mcp_set_track_volume --track_index 4 --volume 0.60
    ableton-live-mcp_set_track_volume --track_index 6 --volume 0.80
    ableton-live-mcp_set_track_volume --track_index 7 --volume 0.70
    ableton-live-mcp_set_track_volume --track_index 8 --volume 0.75
    
    # PASO 6.8: Panoramizacion
    ableton-live-mcp_set_track_pan --track_index 7 --pan -0.2
    ableton-live-mcp_set_track_pan --track_index 8 --pan 0.2
    """)


# =============================================================================
# SECCION 7: MASTERING Y EXPORT
# =============================================================================

def mastering_and_export():
    """
    Mastering final y exportacion.
    """
    print("""
    # PASO 7.1: Master Chain
    ableton-live-mcp_apply_master_chain --preset "standard"
    ableton-live-mcp_set_master_volume --volume 0.9
    
    # PASO 7.2: Quality Check
    ableton-live-mcp_full_quality_check
    ableton-live-mcp_detect_energy_curve
    ableton-live-mcp_balance_sections
    ableton-live-mcp_fix_quality_issues
    
    # PASO 7.3: Validacion
    ableton-live-mcp_validate_project
    ableton-live-mcp_get_production_report
    
    # PASO 7.4: Export
    ableton-live-mcp_export_project \\
        --path "C:\\Users\\Music\\MiTrack_Master.wav" \\
        --format "wav"
    
    ableton-live-mcp_render_stems \\
        --output_dir "C:\\Users\\Music\\Stems"
    
    ableton-live-mcp_render_instrumental \\
        --output_path "C:\\Users\\Music\\MiTrack_Instrumental.wav"
    
    # PASO 7.5: Backup
    ableton-live-mcp_save_as_preset \\
        --name "TemplateReggaeton" \\
        --description "Template completo profesional"
    """)


# =============================================================================
# FLUJO COMPLETO - EJECUCION
# =============================================================================

def run_full_production():
    """
    Ejecuta el flujo completo de produccion.
    """
    print("""
    ╔══════════════════════════════════════════════════════════════════════════════╗
    ║                    FLUJO COMPLETO DE PRODUCCION PROFESIONAL                  ║
    ╚══════════════════════════════════════════════════════════════════════════════╝
    """)
    
    setup_project()
    create_track_structure()
    inject_samples()
    generate_midi_content()
    add_fx_and_automation()
    professional_mixing()
    mastering_and_export()
    
    print("""
    ╔══════════════════════════════════════════════════════════════════════════════╗
    ║                           PRODUCCION COMPLETADA                              ║
    ║                                                                              ║
    ║   Archivos generados:                                                        ║
    ║   - MiTrack_Master.wav     : Mix completo masterizado                      ║
    ║   - Stems/                 : Tracks individuales para mezcla externa       ║
    ║   - MiTrack_Instrumental.wav: Version sin voz                                ║
    ║                                                                              ║
    ║   Preset guardado: TemplateReggaeton                                          ║
    ╚══════════════════════════════════════════════════════════════════════════════╝
    """)


# =============================================================================
# EJEMPLOS ADICIONALES
# =============================================================================

def example_quick_beat():
    """
    Ejemplo: Beat completo en 3 comandos.
    """
    print("""
    # EJEMPLO: Beat completo en 3 comandos
    
    # Comando 1: Setup
    ableton-live-mcp_health_check
    ableton-live-mcp_set_tempo --tempo 95
    
    # Comando 2: Produccion completa automatica
    ableton-live-mcp_generate_complete_reggaeton \\
        --bpm 95 \\
        --key Am \\
        --style perreo \\
        --structure full \\
        --use_samples true
    
    # Comando 3: Master y export
    ableton-live-mcp_apply_master_chain --preset standard
    ableton-live-mcp_export_project --path "beat.wav"
    """)


def example_from_reference():
    """
    Ejemplo: Produccion desde referencia.
    """
    print("""
    # EJEMPLO: Producir copiando estilo de referencia
    
    ableton-live-mcp_generate_from_reference \\
        --reference_audio_path "C:\\referencia.mp3"
    
    # O tambien:
    ableton-live-mcp_produce_from_reference \\
        --audio_path "C:\\referencia.mp3"
    """)


def example_timeline_workflow():
    """
    Ejemplo: Workflow timeline directo.
    """
    print("""
    # EJEMPLO: Workflow timeline directo (ARRANGEMENT-FIRST)
    
    ableton-live-mcp_build_arrangement_timeline \\
        --sections_json '[
            {"name": "Intro", "start_bar": 0, "duration_bars": 8, 
             "tracks": [{"type": "drums", "variation": "minimal"}]},
            {"name": "Verse", "start_bar": 8, "duration_bars": 16,
             "tracks": [{"type": "drums", "variation": "full"}, 
                        {"type": "bass", "variation": "standard"}]},
            {"name": "Chorus", "start_bar": 24, "duration_bars": 8,
             "tracks": [{"type": "drums", "variation": "full"},
                        {"type": "bass", "variation": "melodic"},
                        {"type": "chords", "variation": "i-v-vi-iv"},
                        {"type": "melody", "variation": "lead"}]}
        ]' \\
        --genre reggaeton \\
        --tempo 95 \\
        --key Am
    """)


# =============================================================================
# MAIN - PUNTO DE ENTRADA
# =============================================================================

if __name__ == "__main__":
    print(__doc__)
    
    # Mostrar menu de opciones
    print("""
    MENU DE EJEMPLOS:
    =================
    
    1. Flujo Completo de Produccion Profesional
       -> Ejecuta: run_full_production()
    
    2. Beat Rapido (3 comandos)
       -> Ejecuta: example_quick_beat()
    
    3. Producir desde Referencia
       -> Ejecuta: example_from_reference()
    
    4. Workflow Timeline
       -> Ejecuta: example_timeline_workflow()
    
    
    USO:
    ====
    Copia los comandos que necesites y ejecutalos en tu entorno MCP.
    Cada funcion imprime los comandos correspondientes.
    
    Ejemplo:
        python professional_production.py
        # Ver output y copiar comandos relevantes
    """)
    
    # Ejecutar flujo completo por defecto
    run_full_production()
