import os
import re
import urllib.parse
import hashlib

target_dir = '/Applications/XAMPP/xamppfiles/htdocs/aaa'
file_count = 0
image_count = 0

def process_img_tag(match, path):
    global image_count
    img_tag_original = match.group(0)
    
    # We only want to replace unsplash images
    if 'images.unsplash.com' not in img_tag_original and 'source.unsplash.com' not in img_tag_original:
        return img_tag_original
        
    alt_match = re.search(r'alt="([^"]+)"', img_tag_original)
    if alt_match and alt_match.group(1).strip():
        # use alt text
        prompt = alt_match.group(1).strip()
    else:
        # fallback to file name
        prompt = os.path.splitext(os.path.basename(path))[0].replace('-', ' ')
        
    # remove generic filler words from prompt to increase diversity
    filler = ["course", "certification", "training", "online", "image", "photo", "icon"]
    prompt_words = prompt.split()
    clean_words = [w for w in prompt_words if w.lower() not in filler]
    clean_prompt = " ".join(clean_words) if clean_words else prompt
    
    # generate url using Pollinations AI
    final_prompt = f"{clean_prompt} professional highly detailed conceptual 3D modern digital art"
    encoded_prompt = urllib.parse.quote(final_prompt)
    
    # Create stable seed based on file path and prompt to keep image stable but unique
    seed_str = f"{path}_{prompt}"
    seed = int(hashlib.md5(seed_str.encode()).hexdigest()[:8], 16)
    
    new_src = f'https://image.pollinations.ai/prompt/{encoded_prompt}?width=1000&height=600&seed={seed}&nologo=true'
    
    # Replace the existing src
    # sometimes src can be single quotes or double quotes, and unsplash domains can vary
    new_tag = re.sub(
        r'src=[\"\']https?://(?:images|source)\.unsplash\.com/[^\"\']+[\"\']', 
        f'src="{new_src}"', 
        img_tag_original
    )
    
    if new_tag != img_tag_original:
        image_count += 1
        
    return new_tag

for root, dirs, files in os.walk(target_dir):
    for f in files:
        if f.endswith('.php') or f.endswith('.html'):
            path = os.path.join(root, f)
            
            with open(path, 'r', encoding='utf-8', errors='ignore') as file:
                content = file.read()
            
            # Use lambda to pass path to process_img_tag
            new_content = re.sub(
                r'<img[^>]+>', 
                lambda m: process_img_tag(m, path), 
                content
            )
            
            if new_content != content:
                with open(path, 'w', encoding='utf-8') as write_file:
                    write_file.write(new_content)
                file_count += 1

print(f"Updated {image_count} images in {file_count} files across the website.")
