#!/usr/bin/env python
"""Generate registry code from parsed_plugins.json."""
import json
from pathlib import Path

plugins = json.loads(Path("output/parsed_plugins.json").read_text())

# We prefer VST3 over VST2 when both exist for the same plugin
# Build a map, VST3 overrides VST2
seen_keys = {}
for p in plugins:
    key = p['key']
    if key in seen_keys:
        existing = seen_keys[key]
        # Prefer VST3 over VST2
        if p['is_vst3'] and not existing['is_vst3']:
            seen_keys[key] = p
        # Prefer VST3i/VSTi instruments
        elif p['display_name'].startswith('VST3i') and not existing['display_name'].startswith('VST3i'):
            seen_keys[key] = p
        elif p['display_name'].startswith('VSTi') and not existing['display_name'].startswith('VSTi'):
            seen_keys[key] = p
    else:
        seen_keys[key] = p

# Deduplicated
final = sorted(seen_keys.values(), key=lambda p: p['key'])

print(f"Unique plugins after dedup: {len(final)}")

# Generate registry code
lines = []
lines.append("# Auto-generated from output/all_plugins_v2.rpp (REAPER ground truth)")
lines.append("# Format: key → (display_name, filename, uid_guid)")
lines.append("PLUGIN_REGISTRY: dict[str, tuple[str, str, str]] = {")
for p in final:
    dn = p['display_name']
    fn = p['filename']
    ug = p['uid_guid']
    # Quote filename if it has spaces
    if ' ' in fn or not p['is_vst3']:
        fn_str = f'"{fn}"'
    else:
        fn_str = f'"{fn}"'
    lines.append(f'    "{p["key"]}": (')
    lines.append(f'        "{dn}",')
    lines.append(f'        {fn_str},')
    lines.append(f'        "{ug}",')
    lines.append(f'    ),')
lines.append("}")

# Generate presets code
lines.append("")
lines.append("# Auto-generated preset data from output/all_plugins_v2.rpp")
lines.append("PLUGIN_PRESETS: dict[str, list[str]] = {")
for p in final:
    if p['preset_lines']:
        lines.append(f'    "{p["key"]}": [')
        for pl in p['preset_lines']:
            lines.append(f'        "{pl}",')
        lines.append(f'    ],')
    else:
        lines.append(f'    "{p["key"]}": [],')
lines.append("}")

Path("output/registry_code.py").write_text('\n'.join(lines), encoding='utf-8')
print(f"Generated output/registry_code.py ({len(lines)} lines)")
print(f"\nSample entries:")
for p in final[:5]:
    print(f'  "{p["key"]}": ("{p["display_name"]}", "{p["filename"]}", "{p["uid_guid"]}")')
