#!/usr/bin/env python
"""Parse all_plugins_v2.rpp and generate registry code."""
import re
import json
from pathlib import Path

text = Path("output/all_plugins_v2.rpp").read_text(encoding="utf-8")

# Match VST elements: opening tag through closing >
# The closing > is on its own line with leading whitespace
pattern = r'<VST "([^"]+)" ([^\n]+)\n([\s\S]*?)\n\s*>'
matches = re.findall(pattern, text)

print(f"Total VST elements found: {len(matches)}")

plugins = []
for name, rest, preset_block in matches:
    # Parse rest: filename 0 "" uid_guid ""
    rest_parts = rest.strip().split()
    
    # Find the uid_guid (contains { or <)
    uid_guid = ""
    for part in rest_parts:
        if '{' in part or '<' in part:
            uid_guid = part
            break
    
    # Find filename (second token, may be quoted)
    filename = rest_parts[0].strip('"')
    
    # Clean preset lines
    preset_lines = [line.strip() for line in preset_block.strip().split('\n') if line.strip()]
    # Remove PRESETNAME lines
    preset_lines = [l for l in preset_lines if not l.startswith('PRESETNAME')]
    
    is_vst3 = name.startswith('VST3') or name.startswith('VST3i')
    
    # Generate a short key
    # Remove prefix and vendor
    clean = name.replace('VST3i: ', '').replace('VST3: ', '').replace('VSTi: ', '').replace('VST: ', '')
    # Remove vendor in parens
    clean = re.sub(r'\s*\([^)]+\)', '', clean).strip()
    key = clean.replace(' ', '_')
    
    plugins.append({
        'key': key,
        'display_name': name,
        'filename': filename,
        'uid_guid': uid_guid,
        'is_vst3': is_vst3,
        'preset_lines': preset_lines,
    })

# Save as JSON for use by other scripts
Path("output/parsed_plugins.json").write_text(json.dumps(plugins, indent=2, ensure_ascii=False))
print(f"Saved to output/parsed_plugins.json")

# Print summary
vst3_count = sum(1 for p in plugins if p['is_vst3'])
vst2_count = sum(1 for p in plugins if not p['is_vst3'])
print(f"VST3: {vst3_count}, VST2: {vst2_count}")

# Print a few examples
for p in plugins[:5]:
    print(f"\n  {p['key']}: {p['display_name']}")
    print(f"    filename: {p['filename']}")
    print(f"    uid_guid: {p['uid_guid']}")
    print(f"    preset lines: {len(p['preset_lines'])}")
