import os
import re

# List of files to delete
files_to_delete = [
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.47 PM.jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.46 PM (2).jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.45 PM.jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.49 PM.jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-10 at 2.17.26 PM (1).jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-10 at 2.17.27 PM.jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-10 at 2.17.25 PM (1).jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.46 PM.jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.46 PM (1).jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.48 PM.jpeg",
    r"assets/images/gallery/WhatsApp Image 2026-08-07 at 1.39.47 PM (1).jpeg"
]

# Delete from disk if present
for rel_path in files_to_delete:
    full_p = os.path.normpath(rel_path)
    if os.path.exists(full_p):
        try:
            os.remove(full_p)
            print(f"Deleted file: {full_p}")
        except Exception as e:
            print(f"Error deleting {full_p}: {e}")

# 1. Update publications.html if it referenced any deleted image
if os.path.exists('publications.html'):
    with open('publications.html', 'r', encoding='utf-8') as f:
        pub_c = f.read()
    pub_c = pub_c.replace(
        'WhatsApp Image 2026-08-07 at 1.39.46 PM (2).jpeg',
        'WhatsApp Image 2026-08-07 at 8.42.19 AM (3).jpeg'
    )
    with open('publications.html', 'w', encoding='utf-8') as f:
        f.write(pub_c)

# 2. Update gallery.html
with open('gallery.html', 'r', encoding='utf-8') as f:
    gal_c = f.read()

# Remove the two tab buttons: "Social Service Ministry" and "Province Gatherings"
gal_c = re.sub(
    r'<button class="gallery-tab"[^>]*data-filter="social"[^>]*>.*?</button>\s*',
    '',
    gal_c
)
gal_c = re.sub(
    r'<button class="gallery-tab"[^>]*data-filter="gatherings"[^>]*>.*?</button>\s*',
    '',
    gal_c
)

# In galleryData, filter out deleted images and update categories of remaining images (e.g. Fr. Manoj to pastoral/all)
del_basenames = [os.path.basename(f) for f in files_to_delete]

# Extract galleryData array from gallery.html
def clean_gallery_item(match):
    src_line = match.group(0)
    for db in del_basenames:
        if db in src_line:
            return ""  # Remove deleted image
    # Keep other items, ensure category is valid
    src_line = src_line.replace("'social'", "'pastoral'").replace("'gatherings'", "'pastoral'")
    return src_line

gal_c = re.sub(r'\{\s*src:\s*[\'"][^\'"]+[\'"],\s*category:\s*\[[^\]]+\],\s*alt:\s*[\'"][^\'"]+[\'"]\s*\},?\n?', clean_gallery_item, gal_c)

with open('gallery.html', 'w', encoding='utf-8') as f:
    f.write(gal_c)

print("Updated gallery.html: tabs removed, deleted images removed, remaining images preserved in grid under All and respective categories!")
