import os
import re

target_dir = '/Applications/XAMPP/xamppfiles/htdocs/aaa'
count = 0

def resolve_href(match):
    href = match.group(1)
    
    # Ignore absolute URLs, anchors, emails, scripts
    if href.startswith('http') or href.startswith('#') or href.startswith('mailto:') or href.startswith('javascript:'):
        return match.group(0)
    
    # Ignore already correct extensions
    if href.endswith('.php') or href.endswith('.css') or href.endswith('.js') or href.endswith('.png') or href.endswith('.jpg') or href.endswith('.ico') or href.endswith('.webp'):
        return match.group(0)
    
    # Ignore empty or just '/'
    if href == '' or href == '/':
        return match.group(0)
    
    # Handle cloudflare email protection artifacts by ignoring cdn-cgi
    if 'cdn-cgi' in href:
        return match.group(0)
        
    # Check if there is a query or hash
    base_href = href
    suffix = ''
    if '?' in href:
        base_href, suffix = href.split('?', 1)
        suffix = '?' + suffix
    elif '#' in href:
        base_href, suffix = href.split('#', 1)
        suffix = '#' + suffix
        
    if base_href.endswith('/'):
        # Usually trailing slashes should be stripped or point to index.php
        base_href = base_href[:-1]
        
    if not base_href.endswith('.php') and base_href != '':
        # We assume the internal link was pointing to what is now a .php file
        new_href = base_href + '.php' + suffix
        return f'href="{new_href}"'
    
    return match.group(0)

# Pattern to find href="..."
pattern = re.compile(r'href="([^"]+)"')

for root, dirs, files in os.walk(target_dir):
    for f in files:
        if f.endswith('.php'):
            path = os.path.join(root, f)
            with open(path, 'r', encoding='utf-8', errors='ignore') as file:
                content = file.read()
            
            new_content = pattern.sub(resolve_href, content)
            
            if new_content != content:
                with open(path, 'w', encoding='utf-8') as write_file:
                    write_file.write(new_content)
                count += 1

print(f"Fixed broken links in {count} files.")
