import os, re, json

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]

        # Collect existing var declarations: var xxx ... -> xxx
        existing_vars = set()
        for m in re.finditer(r'\bvar\s+(\w+)\s*=', script):
            existing_vars.add(m.group(1))

        # Find all #{xxx} in SQL templates (triple-quoted strings)
        triple_parts = script.split('"""')
        sql_refs = set()
        for i, part in enumerate(triple_parts):
            if i % 2 == 1:  # inside triple-quoted string (SQL)
                for m in re.finditer(r'#\{(\w+)\}', part):
                    ref = m.group(1)
                    # Skip refs that match existing camelCase vars (e.g., #{userName} -> var userName)
                    if ref not in existing_vars:
                        sql_refs.add(ref)

        if not sql_refs:
            continue

        # Build var declarations to add
        new_vars = []
        for ref in sorted(sql_refs):
            if ref not in existing_vars:
                new_vars.append(f'var {ref} = body.{ref};')
                existing_vars.add(ref)

        if not new_vars:
            continue

        # Insert new var declarations after last existing var declaration (or at the top)
        # Find position: after the last 'var xxx = body.xxx;' or 'var xxx = xxx;' line
        var_lines = [m for m in re.finditer(r'^(\s*)var\s+\w+\s*=\s*(body\.\w+|\w+)\s*;\s*$', script, re.MULTILINE)]
        if var_lines:
            insert_pos = var_lines[-1].end()
        else:
            # No existing var declarations, insert at top of script
            insert_pos = 0

        indent = ''
        if var_lines:
            indent_match = re.match(r'^(\s*)', script[var_lines[-1].start():])
            if indent_match:
                indent = indent_match.group(1)

        new_lines = '\n'.join(f'{indent}{v}' for v in new_vars)
        if insert_pos == 0:
            new_script = new_lines + '\n' + script.lstrip('\n')
        else:
            new_script = script[:insert_pos] + '\n' + new_lines + script[insert_pos:]

        new_content = json.dumps(header, ensure_ascii=False, indent=2)
        new_content += '\n================================\n' + new_script
        with open(fpath, 'w', encoding='utf-8') as f:
            f.write(new_content)
        fixed += 1
        print(f'  Fixed: {os.path.relpath(fpath, SCRIPT_DIR)}')
        print(f'    Added vars: {", ".join(sorted(sql_refs))}')

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