"""
Test script for SampleRotator integration.

This script tests the sample rotation system with the metadata store.
Run this to verify the system is working correctly.
"""

import os
import sys
import logging
from pathlib import Path

# Add project to path
SCRIPT_DIR = Path(__file__).parent.parent.parent
sys.path.insert(0, str(SCRIPT_DIR))

from engines.metadata_store import SampleMetadataStore
from engines.sample_rotator import SampleRotator, create_rotator

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

def test_sample_rotator():
    """Test the SampleRotator with real metadata store."""
    
    # Database path
    db_path = SCRIPT_DIR.parent / "libreria" / "sample_metadata.db"
    
    if not db_path.exists():
        logger.error(f"Metadata database not found at {db_path}")
        logger.info("Run 'analyze_all_bpm' tool first to populate the database")
        return False
    
    # Create rotator
    logger.info(f"Creating SampleRotator with database: {db_path}")
    rotator = create_rotator(
        str(db_path),
        cooldown_scenes=2,
        bpm_tolerance=5.0,
        verbose=True
    )
    
    # Test scene definitions (matching _cmd_build_session_production)
    SCENE_DEFS = [
        ("Intro", 0.20),
        ("Build", 0.50),
        ("Verse", 0.60),
        ("Pre-Chorus", 0.70),
        ("Chorus", 0.95),
        ("Bridge", 0.40),
        ("Drop", 1.00),
        ("Outro", 0.30),
    ]
    
    logger.info("\n=== Testing Sample Rotation Across Scenes ===\n")
    
    # Track selections
    all_selections = {
        "kick": [],
        "snare": [],
        "hihat": [],
        "bass": []
    }
    
    # Simulate scene-by-scene selection
    for scene_idx, (scene_name, energy) in enumerate(SCENE_DEFS):
        logger.info(f"Scene {scene_idx}: {scene_name} (energy={energy:.2f})")
        
        for category in ["kick", "snare", "hihat", "bass"]:
            selected = rotator.select_for_scene(
                category=category,
                scene_energy=energy,
                scene_index=scene_idx,
                count=1,
                bpm_range=(90, 100)  # 95 ± 5 BPM
            )
            
            if selected:
                sample_name = Path(selected[0].path).name
                all_selections[category].append((scene_name, sample_name, energy))
                logger.info(f"  {category:6s}: {sample_name}")
            else:
                logger.info(f"  {category:6s}: [no match found]")
        
        print()  # Blank line between scenes
    
    # Generate usage report
    logger.info("\n=== Usage Report ===\n")
    report = rotator.get_usage_report()
    logger.info(f"Total scenes processed: {report['total_scenes']}")
    
    for category, stats in report['categories'].items():
        logger.info(f"\n{category.upper()}:")
        logger.info(f"  Total samples tracked: {stats['total_samples']}")
        logger.info(f"  Used once: {stats['samples_used_once']}")
        logger.info(f"  Used multiple times: {stats['samples_used_multiple']}")
    
    # Check for consecutive repetition
    logger.info("\n=== Repetition Analysis ===\n")
    for category, selections in all_selections.items():
        repetitions = []
        for i in range(1, len(selections)):
            prev_name = selections[i-1][1]
            curr_name = selections[i][1]
            if prev_name == curr_name:
                repetitions.append((selections[i-1][0], selections[i][0], curr_name))
        
        if repetitions:
            logger.warning(f"{category}: {len(repetitions)} consecutive repetitions detected")
            for prev_scene, curr_scene, sample in repetitions:
                logger.warning(f"  {prev_scene} → {curr_scene}: {sample}")
        else:
            logger.info(f"{category}: ✓ No consecutive repetitions (good!)")
    
    # Summary
    logger.info("\n=== Summary ===\n")
    total_selections = sum(len(s) for s in all_selections.values())
    unique_samples = sum(len(set(s[1] for s in selections)) for selections in all_selections.values())
    
    logger.info(f"Total sample selections: {total_selections}")
    logger.info(f"Unique samples used: {unique_samples}")
    logger.info(f"Variety ratio: {unique_samples/total_selections*100:.1f}%")
    
    if unique_samples / total_selections > 0.7:
        logger.info("✓ Excellent sample variety!")
    else:
        logger.info("⚠ Sample variety could be improved")
    
    return True


if __name__ == "__main__":
    print("=" * 70)
    print("SampleRotator Integration Test")
    print("=" * 70)
    print()
    
    success = test_sample_rotator()
    
    print()
    print("=" * 70)
    if success:
        print("✓ Test completed successfully")
    else:
        print("⚠ Test completed with warnings")
    print("=" * 70)
