#!/usr/bin/env python
"""Generate fixed .rpp files from example RPP templates.

Extracts track/FX chain structures from the example .rpp files,
fixes GUIDs using real values from reaper-vstplugins64.ini,
strips invalid PARAM lines, and generates working .rpp files.

Usage:
    python scripts/generate_from_template.py --all
    python scripts/generate_from_template.py --template TU_DIABLO --output output/tu_diablo_fixed.rpp
    python scripts/generate_from_template.py --template DEL_LUNE --output output/del_lune_fixed.rpp
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

# Ensure project root on path
_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(_ROOT))

from src.composer.templates import extract_template, generate_rpp


TEMPLATES: dict[str, dict] = {
    "TU_DIABLO": {
        "source": "ejemplos/TU_DIABLO_ITHAN_NY.rpp",
        "output": "output/tu_diablo_fixed.rpp",
        "description": "TU_DIABLO_ITHAN_NY.rpp — 99 BPM E minor, Drill chileno",
    },
    "DEL_LUNE": {
        "source": "ejemplos/DEL_LUNE_AL_FINDE_ITHAN_NY_JULIANNO_SOSA.rpp",
        "output": "output/del_lune_fixed.rpp",
        "description": "DEL_LUNE_AL_FINDE_*.rpp — 100 BPM B major, Reggaeton moderno",
    },
}


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Generate fixed .rpp files from example templates."
    )
    parser.add_argument(
        "--all",
        action="store_true",
        help="Generate all templates (TU_DIABLO and DEL_LUNE)",
    )
    parser.add_argument(
        "--template",
        choices=list(TEMPLATES.keys()),
        help="Specific template to generate",
    )
    parser.add_argument(
        "--output",
        help="Override output path",
    )
    parser.add_argument(
        "--list",
        action="store_true",
        help="List available templates",
    )
    args = parser.parse_args()

    if args.list:
        print("Available templates:")
        for key, info in TEMPLATES.items():
            print(f"  {key}: {info['description']}")
            print(f"    Source: {info['source']}")
            print(f"    Output: {info['output']}")
        return

    templates_to_run = []
    if args.all:
        templates_to_run = list(TEMPLATES.keys())
    elif args.template:
        templates_to_run = [args.template]
    else:
        # Default: generate all
        templates_to_run = list(TEMPLATES.keys())

    for key in templates_to_run:
        info = TEMPLATES[key]
        source_path = _ROOT / info["source"]
        output_path = Path(args.output) if args.output else _ROOT / info["output"]

        print(f"\n[{key}]")
        print(f"  Source:  {source_path}")
        print(f"  Output:  {output_path}")

        if not source_path.exists():
            print(f"  ERROR: Source file not found: {source_path}", file=sys.stderr)
            continue

        try:
            # Extract template from source RPP
            print(f"  Extracting template...")
            template = extract_template(source_path)
            print(f"  Tracks found: {len(template.tracks)}")
            for track in template.tracks:
                print(f"    - {track.name}: {len(track.plugins)} plugins")
                for plugin in track.plugins:
                    print(f"        {plugin.name} ({plugin.path})")

            # Generate fixed RPP
            print(f"  Generating RPP...")
            generate_rpp(template, output_path)
            print(f"  SUCCESS: {output_path}")

        except Exception as e:
            print(f"  ERROR: {e}", file=sys.stderr)
            import traceback
            traceback.print_exc()


if __name__ == "__main__":
    main()
