#!/usr/bin/env python3
"""Migration: auth_db.users -> syndicos.auth_users"""
import re, os, subprocess

BETA = os.path.expanduser('~/beta')

def find_files():
    r = subprocess.run(['grep','-rln','getAuthConnection',BETA,'--include=*.php'],
                       capture_output=True, text=True)
    return sorted(f for f in r.stdout.strip().split('\n')
                  if f and 'vendor/' not in f and 'Controllers/Controllers/' not in f)

def get_auth_vars(content):
    return set(re.findall(r'\$(\w+)\s*=\s*.*?getAuthConnection\(\)', content))

def migrate_file(path):
    with open(path) as f:
        content = f.read()
    auth_vars = get_auth_vars(content)
    if not auth_vars:
        return 0
    lines = content.split('\n')
    changes = 0
    for i, line in enumerate(lines):
        for v in auth_vars:
            if '$' + v + '->' in line or '$' + v + ' ->' in line:
                nl = line
                nl = re.sub(r'FROM users\b', 'FROM auth_users', nl)
                nl = re.sub(r'INTO users\b', 'INTO auth_users', nl)
                nl = re.sub(r'INTO users\(', 'INTO auth_users(', nl)
                nl = re.sub(r'UPDATE users\b', 'UPDATE auth_users', nl)
                nl = re.sub(r'JOIN users\b', 'JOIN auth_users', nl)
                if nl != line:
                    lines[i] = nl
                    changes += 1
    if changes:
        with open(path, 'w') as f:
            f.write('\n'.join(lines))
    return changes

def fix_database_php():
    p = os.path.join(BETA, 'core', 'Database.php')
    with open(p) as f:
        c = f.read()
    old = c
    # Try exact match first
    c = c.replace('return self::$authPdo;',
                   'return self::getSyndicosConnection(); /* migration: auth -> syndicos.auth_users */', 1)
    if c == old:
        c = re.sub(r'return\s+self::\$authPdo\s*;',
                    'return self::getSyndicosConnection(); /* migration */', c, count=1)
    if c != old:
        with open(p, 'w') as f:
            f.write(c)
        return True
    return False

def main():
    print("=== Migration: auth_db.users -> syndicos.auth_users ===")

    print("\n[1] Database.php...")
    if fix_database_php():
        print("  OK: getAuthConnection() -> getSyndicosConnection()")
    else:
        print("  WARN: could not update (check manually)")

    print("\n[2] Finding files...")
    files = find_files()
    print(f"  {len(files)} files")

    print("\n[3] Replacing SQL table names...")
    total = 0
    for path in files:
        if path.endswith('Database.php'):
            continue
        n = migrate_file(path)
        rel = path.replace(BETA + '/', '')
        if n:
            print(f"  OK {rel} ({n})")
            total += n
    print(f"\n  Total: {total} SQL replacements")

    print("\n[4] Verification...")
    issues = 0
    for path in files:
        if path.endswith('Database.php'):
            continue
        with open(path) as f:
            c = f.read()
        vv = get_auth_vars(c)
        for i, line in enumerate(c.split('\n')):
            for v in vv:
                if ('$' + v + '->' in line or '$' + v + ' ->' in line):
                    if re.search(r'(?:FROM|INTO|UPDATE|JOIN)\s+users\b', line):
                        rel = path.replace(BETA + '/', '')
                        print(f"  REMAINING: {rel}:{i+1}: {line.strip()[:100]}")
                        issues += 1
    print(f"  {'All clear!' if not issues else f'{issues} remaining'}")

if __name__ == '__main__':
    main()
