import re
from pathlib import Path

# Paths to replace (must start with / and not have v1/erp)
paths = [
    '/agent-models', '/banking', '/customers', '/dashboard', '/dhs', '/documents',
    '/documents-dashboard', '/drawing-takeoff', '/employees', '/equipment', '/erp',
    '/finance', '/invoices', '/login', '/material-price-comparison', '/material-prices',
    '/partners', '/projects', '/readiness', '/settings', '/site-diary', '/site-pwa',
    '/state-prices', '/takeoff', '/users', '/vendors', '/war-room', '/wbs', '/zalo-crm'
]

html_dir = Path('app/static')

def replace_links(text):
    # Sort paths by length descending so we match /dashboard/settings before /dashboard
    sorted_paths = sorted(paths, key=len, reverse=True)
    
    # We want to match:
    # href="/dashboard" or href='/dashboard'
    # window.location.href='/dashboard'
    # action="/dashboard"
    # ONLY if it's an exact match of the path or followed by / or ? or # or end of quote
    
    for p in sorted_paths:
        # Match href="/path" or href='/path'
        # Pattern explanation: (href=|action=|window\.location\.href=)(["'])({p})([/"'?#]|$)
        # Wait, if p is "/dashboard", and text has "/dashboard/users", we should match the full path if we iterate properly.
        # However, our paths list ALREADY includes all the /dashboard/... subpaths if we just do a regex replace on the prefix.
        
        # Actually, if we just replace: (href=|action=|window\.location\.href=)(['"])(/.*?)(['"])
        pass
        
    # Better approach: parse the string and replace any prefix that matches one of the known paths
    # (Because there might be /dashboard/something_new not in the list)
    
    def replacer(match):
        attr = match.group(1)
        quote = match.group(2)
        url = match.group(3)
        
        if url.startswith('/v1/erp') or url.startswith('/static') or url.startswith('/storage') or url.startswith('/docs'):
            return match.group(0)
            
        # Check if it starts with any of our known prefixes
        for p in ['/dashboard', '/login', '/settings'] + sorted_paths:
            if url == p or url.startswith(p + '/') or url.startswith(p + '?') or url.startswith(p + '#'):
                return f"{attr}{quote}/v1/erp{url}{quote}"
                
        return match.group(0)

    # regex to match href="..." or action="..." or window.location.href="..."
    pattern = re.compile(r'(href=|action=|window\.location\.href=)(["\'])(/[^"\']*)(["\'])')
    return pattern.sub(replacer, text)

for file_path in html_dir.glob('**/*.html'):
    original_text = file_path.read_text(encoding='utf-8')
    new_text = replace_links(original_text)
    if original_text != new_text:
        file_path.write_text(new_text, encoding='utf-8')
        print(f"Updated {file_path.name}")
        
print("HTML link updates complete.")
