import glob
import re

files = glob.glob('templates/*/detail.html') + ['templates/detail.html']

for filepath in files:
    with open(filepath, 'r') as f:
        content = f.read()

    # We need to replace:
    # data-bs-toggle="modal" data-bs-target="#imageModal" onclick="showImage(this.querySelector('img').src)"
    # with:
    # onclick="openGallery([this.querySelector('img') ? this.querySelector('img').src : ''], 0)"
    
    # Or in some places:
    # data-bs-toggle="modal" data-bs-target="#imageModal" onclick="showImage(this.querySelector('img') ? this.querySelector('img').src : '')"
    # and:
    # data-bs-toggle="modal" data-bs-target="#imageModal" onclick="showImage(this.src)"

    # Also there are instances like:
    # onclick="showImage(this.querySelector('img').src)"
    # and
    # onclick="showImage(this.src)"
    
    content = re.sub(
        r'data-bs-toggle="modal"\s+data-bs-target="#imageModal"\s*onclick="showImage\([^"]+\)"',
        r'onclick="openGallery([this.querySelector(\'img\') ? this.querySelector(\'img\').src : this.src || \'\'], 0)"',
        content
    )
    
    # Catch any remaining data-bs-toggle
    content = re.sub(
        r'data-bs-toggle="modal"\s+data-bs-target="#imageModal"',
        r'',
        content
    )

    # Catch any remaining showImage(...)
    content = re.sub(
        r'onclick="showImage\([^"]+\)"',
        r'onclick="openGallery([this.querySelector(\'img\') ? this.querySelector(\'img\').src : this.src || \'\'], 0)"',
        content
    )

    # Remove the old function showImage(src) { ... }
    content = re.sub(
        r'function showImage\(src\) \{\s*document\.getElementById\(\'modalImage\'\)\.src = src;\s*\}',
        r'',
        content
    )

    with open(filepath, 'w') as f:
        f.write(content)
        
    print(f"Fixed {filepath}")
