import os
import re
from PIL import Image

def update_social_links():
    html_files = [f for f in os.listdir('.') if f.endswith('.html')]
    fb_target = 'https://www.facebook.com/profile.php?id=61593681501900'
    insta_target = 'https://www.instagram.com/torranchiprovince/'
    
    updated_files = 0
    for fname in html_files:
        with open(fname, 'r', encoding='utf-8') as f:
            c = f.read()
        
        # Replace facebook links in footer
        c = re.sub(r'href=["\']https?://(?:www\.)?facebook\.com[^"\']*["\']', f'href="{fb_target}"', c)
        c = re.sub(r'"https?://(?:www\.)?facebook\.com[^"]*"', f'"{fb_target}"', c)
        
        # Replace instagram links in footer
        c = re.sub(r'href=["\']https?://(?:www\.)?instagram\.com[^"\']*["\']', f'href="{insta_target}"', c)
        c = re.sub(r'"https?://(?:www\.)?instagram\.com[^"]*"', f'"{insta_target}"', c)
        
        with open(fname, 'w', encoding='utf-8') as f:
            f.write(c)
        updated_files += 1
        
    print(f"Updated social links in all {updated_files} HTML files.")

def optimize_images():
    img_dir = r"d:\iss\Franciscan Society\assets\images"
    total_saved = 0
    optimized_count = 0
    
    for root, dirs, files in os.walk(img_dir):
        for f in files:
            ext = f.lower().split('.')[-1]
            if ext in ['jpg', 'jpeg', 'png']:
                fp = os.path.join(root, f)
                orig_size = os.path.getsize(fp)
                
                # Skip if already very small (< 100KB)
                if orig_size < 100 * 1024:
                    continue
                    
                try:
                    with Image.open(fp) as img:
                        # Max dimension
                        max_dim = 1400 if 'hero' in f.lower() else 1000
                        if 'friar' in fp.lower():
                            max_dim = 400
                            
                        w, h = img.size
                        if max(w, h) > max_dim:
                            img.thumbnail((max_dim, max_dim), Image.Resampling.LANCZOS)
                            
                        if ext in ['jpg', 'jpeg']:
                            if img.mode in ('RGBA', 'P'):
                                img = img.convert('RGB')
                            img.save(fp, "JPEG", quality=82, optimize=True)
                        elif ext == 'png':
                            if img.mode not in ('RGBA', 'RGB'):
                                img = img.convert('RGBA')
                            img.save(fp, "PNG", optimize=True)
                            
                        new_size = os.path.getsize(fp)
                        saved = orig_size - new_size
                        if saved > 0:
                            total_saved += saved
                            optimized_count += 1
                except Exception as e:
                    print(f"Error optimizing {fp}: {e}")
                    
    print(f"Optimized {optimized_count} images, total bandwidth saved: {total_saved / (1024*1024):.2f} MB")

def add_lazy_loading_and_speed_tweaks():
    html_files = [f for f in os.listdir('.') if f.endswith('.html')]
    for fname in html_files:
        with open(fname, 'r', encoding='utf-8') as f:
            c = f.read()
            
        # Ensure img tags have loading="lazy" decoding="async"
        def add_lazy(match):
            tag = match.group(0)
            if 'loading=' not in tag and 'logo.svg' not in tag and 'hero-' not in tag:
                tag = tag.replace('<img', '<img loading="lazy" decoding="async"', 1)
            elif 'loading=' in tag and 'decoding=' not in tag:
                tag = tag.replace('loading="lazy"', 'loading="lazy" decoding="async"')
            return tag
            
        c = re.sub(r'<img\s+[^>]+>', add_lazy, c)
        
        with open(fname, 'w', encoding='utf-8') as f:
            f.write(c)
            
    print(f"Added lazy loading & async decoding to images in all {len(html_files)} HTML files.")

if __name__ == '__main__':
    update_social_links()
    optimize_images()
    add_lazy_loading_and_speed_tweaks()
