import os
import re
from pathlib import Path
root = Path(r'c:\Users\UTILISATEUR\Desktop\htdocs')
changed = []

for p in root.rglob('*.php'):
    if p.name == 'db.php':
        continue
    if 'med' in p.parts:
        continue

    text = p.read_text(encoding='utf8')
    if '$servername' not in text or '$username_db' not in text or '$password_db' not in text or '$dbname' not in text:
        continue
    lines = text.splitlines()
    start = None
    for i, line in enumerate(lines):
        if re.match(r'^\s*\$servername\s*=\s*', line):
            start = i
            break
    if start is None:
        continue

    def find_block(lines, start):
        pdo_line = None
        mysqli_line = None
        try_line = None
        for i in range(start, len(lines)):
            line = lines[i]
            if pdo_line is None and re.search(r'new\s+PDO', line):
                pdo_line = i
            if mysqli_line is None and re.search(r'new\s+mysqli', line):
                mysqli_line = i
            if try_line is None and re.search(r'\btry\b', line):
                try_line = i
            if pdo_line is not None and mysqli_line is not None:
                break
        if pdo_line is not None:
            if try_line is None or try_line > pdo_line:
                return pdo_line, pdo_line
            brace = 0
            for i in range(try_line, len(lines)):
                brace += lines[i].count('{') - lines[i].count('}')
                if brace == 0 and i > try_line:
                    return try_line, i
            return try_line, len(lines) - 1
        if mysqli_line is not None:
            end = mysqli_line
            if end + 1 < len(lines) and re.match(r'^\s*if\s*\(\s*\$[a-zA-Z_]+\s*->\s*connect_error\s*\)', lines[end+1]):
                brace = 0
                for j in range(end + 1, len(lines)):
                    brace += lines[j].count('{') - lines[j].count('}')
                    if brace == 0 and j > end + 1:
                        end = j
                        break
            return start, end
        return None, None

    end_start, end = find_block(lines, start)
    if end_start is None:
        continue
    if 'admin' in p.parts:
        include_line = "require_once __DIR__ . '/../db.php';"
    else:
        include_line = "require_once __DIR__ . '/db.php';"
    new_lines = lines[:start] + [include_line] + lines[end+1:]
    p.write_text('\n'.join(new_lines) + ('\n' if text.endswith('\n') else ''), encoding='utf8')
    changed.append(str(p.relative_to(root)))

print('changed files:', len(changed))
for f in changed:
    print(f)
