import os
import sys
import logging

# Ensure app is in path
sys.path.insert(0, "/app")

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("test_sf_convert")

from app.core.soundfont_converter import SoundFontConverter

def test():
    sf2_dir = "/app/app/storage/soundfonts"
    sf2_files = [os.path.join(sf2_dir, f) for f in os.listdir(sf2_dir) if f.endswith(".sf2") and "_decomp" not in f]
    if not sf2_files:
        logger.error("No SF2 files found in /app/app/storage/soundfonts")
        return

    sf2_path = sf2_files[0]
    logger.info(f"Testing with SF2 file: {sf2_path}")

    converter = SoundFontConverter()
    
    # Check ffmpeg encoder support
    has_ogg = converter._check_ffmpeg_ogg()
    logger.info(f"ffmpeg with libvorbis available: {has_ogg}")

    # Convert SF2 -> SF3
    sf3_path = sf2_path.replace(".sf2", ".sf3")
    if os.path.exists(sf3_path):
        os.remove(sf3_path)

    logger.info("Converting SF2 -> SF3...")
    result_path = converter.convert_sf2_to_sf3(sf2_path)
    logger.info(f"Result path from convert_sf2_to_sf3: {result_path}")
    
    if result_path.endswith(".sf3"):
        logger.info(f"SF3 file exists: {os.path.exists(sf3_path)}")
        if os.path.exists(sf3_path):
            logger.info(f"SF3 size: {os.path.getsize(sf3_path)} bytes")
            # Verify if it plays audio
            plays = converter._sf3_plays_audio(sf3_path)
            logger.info(f"SF3 plays audio (pyfluidsynth verify): {plays}")
            
            # Now test decompression back to SF2
            decomp_sf2 = sf3_path.replace(".sf3", "_decomp.sf2")
            if os.path.exists(decomp_sf2):
                os.remove(decomp_sf2)
            
            logger.info("Decompressing SF3 -> SF2...")
            try:
                decomp_result = converter.sf3_to_sf2(sf3_path, decomp_sf2)
                logger.info(f"Decompress result path: {decomp_result}")
                if os.path.exists(decomp_sf2):
                    logger.info(f"Decompressed SF2 size: {os.path.getsize(decomp_sf2)} bytes")
                    # Check if it plays
                    decomp_plays = converter._sf3_plays_audio(decomp_sf2)
                    logger.info(f"Decompressed SF2 plays audio: {decomp_plays}")
            except Exception as e:
                logger.error(f"Decompression failed: {e}", exc_info=True)
    else:
        logger.warning("Conversion did not produce an SF3 path.")

if __name__ == "__main__":
    test()
