import os, json, re

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
API_DIR = os.path.join(SCRIPT_DIR, 'data', 'magic-api', 'api')

fixed = 0
for root, dirs, files in os.walk(API_DIR):
    for fname in sorted(files):
        if not fname.endswith('.ms'):
            continue
        fpath = os.path.join(root, fname)
        with open(fpath, 'r', encoding='utf-8') as f:
            content = f.read()

        parts = content.split('================================\n', 1)
        if len(parts) != 2:
            continue
        try:
            header = json.loads(parts[0].strip())
        except:
            continue
        if header.get('method') != 'POST':
            continue

        script = parts[1]
        old_script = script

        # Split multi-statement lines
        script = re.sub(r';(var\s)', r';\n\1', script)
        script = re.sub(r';(assert\s)', r';\n\1', script)
        script = re.sub(r';(if\s*\()', r';\n\1', script)

        if script != old_script:
            new_content = json.dumps(header, ensure_ascii=False, indent=2)
            new_content += '\n================================\n' + script
            with open(fpath, 'w', encoding='utf-8') as f:
                f.write(new_content)
            fixed += 1
            print(f'  Split: {os.path.relpath(fpath, SCRIPT_DIR)}')

print(f'\nFiles fixed: {fixed}')
