#!/usr/bin/env python3
"""
Separa MIDI piano em duas tracks: Left Hand (notas < C4) e Right Hand (notas >= C4)
Usa pretty_midi (já instalado no venv do basic-pitch)
"""
import pretty_midi
import os, sys

# C4 = 60 no MIDI
C4 = 60

def split_hands(input_midi_path, output_path=None):
    midi_data = pretty_midi.PrettyMIDI(input_midi_path)

    # Pega todas as notas de todos os instrumentos
    all_notes = []
    for instrument in midi_data.instruments:
        for note in instrument.notes:
            all_notes.append(note)

    if not all_notes:
        print(f"  ⚠ Nenhuma nota encontrada em {input_midi_path}")
        return False

    # Cria novo MIDI com 2 instrumentos (piano)
    new_midi = pretty_midi.PrettyMIDI(initial_tempo=midi_data.estimate_tempo())

    # Mão esquerda - canal 1, programa 0 (Acoustic Grand Piano)
    left_hand = pretty_midi.Instrument(program=0, name="Left Hand")

    # Mão direita - canal 0, programa 0
    right_hand = pretty_midi.Instrument(program=0, name="Right Hand")

    for note in all_notes:
        # Clona a nota
        new_note = pretty_midi.Note(
            velocity=note.velocity,
            pitch=note.pitch,
            start=note.start,
            end=note.end
        )
        if note.pitch < C4:
            left_hand.notes.append(new_note)
        else:
            right_hand.notes.append(new_note)

    new_midi.instruments.append(right_hand)
    new_midi.instruments.append(left_hand)

    if output_path is None:
        base, ext = os.path.splitext(input_midi_path)
        output_path = f"{base}_hands.mid"

    new_midi.write(output_path)

    lh_notes = len(left_hand.notes)
    rh_notes = len(right_hand.notes)
    print(f"  ✅ {os.path.basename(input_midi_path)} → {os.path.basename(output_path)}")
    print(f"     Left Hand: {lh_notes} notas | Right Hand: {rh_notes} notas")
    return True

if __name__ == "__main__":
    input_dir = sys.argv[1] if len(sys.argv) > 1 else "/root/ff7-piano-transcribed"
    output_dir = sys.argv[2] if len(sys.argv) > 2 else "/root/ff7-piano-split"

    os.makedirs(output_dir, exist_ok=True)

    midi_files = sorted([f for f in os.listdir(input_dir) if f.endswith('.mid')])
    print(f"🎹 Separando {len(midi_files)} MIDIs em mão direita/esquerda...\n")

    for fname in midi_files:
        in_path = os.path.join(input_dir, fname)
        out_path = os.path.join(output_dir, fname.replace('.mid', '_split.mid'))
        split_hands(in_path, out_path)

    print(f"\n✨ Todos salvos em: {output_dir}")
