#!/usr/bin/env python3
"""
Fix remaining broken images in srcSet and Next.js image proxy URLs.
These have the pattern:
  /_next/image?url=https%3A%2F%2Fimages.unsplash.com/photo-1516321318423-f06f85e504b3...%2FFilename.webp

We replace the whole srcSet with a clean single src pointing to the CDN.
Also fix the broken banner top image and homepage hero image.
"""
import os
import re

BASE_DIR = '/Applications/XAMPP/xamppfiles/htdocs/aaa'

# Pattern for broken /_next/image?url= proxy with unsplash photo embedded
NEXT_IMAGE_PROXY_PATTERN = re.compile(
    r'/_next/image\?url=https%3A%2F%2Fimages\.unsplash\.com%2Fphoto-1516321318423-f06f85e504b3[^&]*%2F([^&"\'>\s]+)',
    re.IGNORECASE
)

# Also fix srcSet attributes that contain this broken pattern 
SRCSET_BROKEN_PATTERN = re.compile(
    r'srcSet="[^"]*images\.unsplash\.com/photo-1516321318423-f06f85e504b3[^"]*"',
    re.IGNORECASE  
)

# Fix the top banner image in header - replace with a nice dark gradient banner
TOP_BANNER_OLD_SRCSET = re.compile(
    r'srcSet="[^"]*Top_WebBanner[^"]*"',
    re.IGNORECASE
)
TOP_BANNER_OLD_SRC = re.compile(
    r'src="_next/Top_WebBanner[^"]*"',
    re.IGNORECASE
)

# Fix homepage hero banner
HERO_BANNER_OLD_SRCSET = re.compile(
    r'srcSet="[^"]*Homepage_Banner_Agentic_AI[^"]*"',
    re.IGNORECASE
)
HERO_BANNER_OLD_SRC = re.compile(
    r'src="_next/Homepage_Banner_Agentic_AI[^"]*"',
    re.IGNORECASE
)

fixed = 0

def fix_file(filepath):
    global fixed
    try:
        with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        original = content
        
        # Fix /_next/image proxy URLs - extract the filename and point to CDN
        content = NEXT_IMAGE_PROXY_PATTERN.sub(
            lambda m: 'https://d2o2utebsixu4k.cloudfront.net/' + m.group(1).replace('%20', ' ').replace('%2B', '+'),
            content
        )
        
        # Remove broken srcSet attributes entirely (they're for responsive loading, src is enough)
        # Only remove when it contains the unsplash broken photo
        # We just blank these out
        content = SRCSET_BROKEN_PATTERN.sub('srcSet=""', content)
        
        # Fix top banner srcSet 
        content = TOP_BANNER_OLD_SRCSET.sub('srcSet=""', content)
        # Fix top banner src - replace with a solid colored promotional banner
        content = TOP_BANNER_OLD_SRC.sub(
            'src="https://d2o2utebsixu4k.cloudfront.net/Top_WebBanner_13Apr-f0e673e211d348daa0512720d543f139.webp"',
            content
        )
        
        # Fix homepage hero banner srcSet
        content = HERO_BANNER_OLD_SRCSET.sub('srcSet=""', content)
        # Fix homepage hero banner src
        content = HERO_BANNER_OLD_SRC.sub(
            'src="https://d2o2utebsixu4k.cloudfront.net/Homepage_Banner_Agentic_AI_50-df3ce4d36d4f4634b5a983cc3a7b532a.webp"',
            content
        )

        # Fix any remaining broken _next/filename.jpeg?url=... patterns  
        broken_next_src = re.compile(r'src="_next/[^"]*\?url=https%3A%2F%2Fimages\.unsplash[^"]*"')
        content = broken_next_src.sub('src=""', content)
        
        if content != original:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            fixed += 1
            print(f"  Fixed: {os.path.relpath(filepath, BASE_DIR)}")
    except Exception as e:
        print(f"  ERROR: {filepath}: {e}")

# Only process the main files that have these remaining issues
target_files = [
    os.path.join(BASE_DIR, 'header.php'),
    os.path.join(BASE_DIR, 'index.php'),
]

# Also scan all PHP files quickly
for root, dirs, files in os.walk(BASE_DIR):
    dirs[:] = [d for d in dirs if not d.startswith('.')]
    for fn in files:
        if fn.endswith(('.php', '.html')):
            fp = os.path.join(root, fn)
            if fp not in target_files:
                target_files.append(fp)

print(f"Scanning {len(target_files)} files...")
for fp in target_files:
    fix_file(fp)

print(f"\nDone! Fixed {fixed} files.")
