#!/usr/bin/env python3
"""Construye índice espectral de la librería de samples."""
import json
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from spectral_engine import get_spectral_engine

LIBRARY = r"C:\ProgramData\Ableton\Live 12 Suite\Resources\MIDI Remote Scripts\libreria\reggaeton"
INDEX_FILE = os.path.join(os.path.dirname(__file__), "spectral_index.json")

def build():
    eng = get_spectral_engine()
    index = {}
    count = 0
    for root, dirs, files in os.walk(LIBRARY):
        for f in files:
            if f.lower().endswith(('.wav','.aif','.aiff','.mp3')):
                path = os.path.join(root, f)
                prof = eng.analyze(path)
                if prof:
                    index[path] = {
                        "centroid": prof.centroid_mean,
                        "centroid_std": prof.centroid_std,
                        "rolloff": prof.rolloff_85,
                        "flux": prof.flux_mean,
                        "mfcc": prof.mfcc,
                        "rms": prof.rms,
                        "flatness": prof.spectral_flatness,
                        "duration": prof.duration,
                        "genre_hints": prof.genre_hints
                    }
                    print(f"OK: {f}")
                    count += 1
    with open(INDEX_FILE, 'w') as fh:
        json.dump(index, fh, indent=2)
    print(f"Índice guardado: {count} samples en {INDEX_FILE}")

if __name__ == "__main__":
    build()