"""
rebuild_index.py - Reconstruir índice de embeddings para organized_samples
"""
import sys
import logging
from pathlib import Path

logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logger = logging.getLogger(__name__)

# Add MCP_Server to path
sys.path.insert(0, str(Path(__file__).parent / "MCP_Server"))

from vector_manager import VectorManager

def rebuild_index():
    # Ruta correcta - organized_samples está en el root de MIDI Remote Scripts
    library_path = Path("C:/ProgramData/Ableton/Live 12 Suite/Resources/MIDI Remote Scripts/librerias/organized_samples")

    logger.info(f"Reconstruyendo indice para: {library_path}")
    logger.info(f"La ruta existe: {library_path.exists()}")

    if library_path.exists():
        # Listar subcarpetas con archivos
        total_wav = 0
        for subdir in library_path.rglob("*"):
            if subdir.is_dir():
                wav_files = list(subdir.glob("*.wav"))
                if wav_files:
                    logger.info(f"  {subdir.relative_to(library_path)}: {len(wav_files)} archivos .wav")
                    total_wav += len(wav_files)
        logger.info(f"Total: {total_wav} archivos .wav")

    logger.info("=" * 60)

    # Eliminar índice existente si hay
    index_file = library_path / ".sample_embeddings.json"
    if index_file.exists():
        logger.info(f"Eliminando indice antiguo: {index_file}")
        index_file.unlink()

    # Crear nuevo VectorManager (auto-rebuild)
    vm = VectorManager(str(library_path), skip_audio_analysis=False)

    logger.info("=" * 60)
    logger.info(f"Indice reconstruido con {len(vm.metadata)} samples")
    logger.info(f"Archivo: {index_file}")

    return len(vm.metadata)

if __name__ == "__main__":
    count = rebuild_index()
    print(f"\nIndice listo: {count} samples")
