from pathlib import Path
from bs4 import BeautifulSoup
import shutil, re

base = Path('/Users/iggy/.hermes/profiles/ignite_team/outbound')
html_path = base / 'st-catherines-rendered-template-text-only.html'
backup_path = base / 'st-catherines-rendered-template-text-only.before-stc-images.html'
assets_dir = base / 'stc-assets'

if not backup_path.exists():
    shutil.copy2(html_path, backup_path)

html = html_path.read_text(errors='ignore')
soup = BeautifulSoup(html, 'html.parser')

# Keep local assets relative so the page works from the existing local server.
logo_src = 'stc-assets/logo.svg'
image_files = [
    'stc-01.png',  # homepage hero
    'stc-11.png',  # visit/tour hero
    'stc-09.jpg',  # boarding/community
    'stc-08.jpg',  # senior school
    'stc-02.jpg',  # campus / students
    'stc-03.jpg',  # music school
    'stc-04.jpg',  # learning
    'stc-05.jpg',  # students
    'stc-06.jpg',  # school life
    'stc-07.jpg',  # school life
    'stc-10.jpeg', # co-curricular
    'stc-12.jpg',  # tour/student
    'stc-13.jpg',  # campus/student
    'stc-14.jpg',  # school life
    'stc-15.jpg',  # school life
]
image_srcs = [f'stc-assets/{name}' for name in image_files if (assets_dir / name).exists()]
if not image_srcs:
    raise SystemExit('No replacement images found')

# Replace Zeekr logo anchors with the St Catherine's SVG logo.
logo_replacements = 0
for a in soup.select('a.logo, a.logo-center'):
    classes = a.get('class') or []
    if 'logo' in classes or 'logo-center' in classes:
        a.clear()
        a['href'] = 'https://www.stcatherines.net.au/'
        a['aria-label'] = "St Catherine's School logo"
        img = soup.new_tag('img')
        img['src'] = logo_src
        img['alt'] = "St Catherine's School"
        img['class'] = 'stc-logo-svg'
        a.append(img)
        logo_replacements += 1

# Replace image tags that point at Zeekr/DatoCMS/rendered asset paths.
def is_zeekr_asset(value: str) -> bool:
    if not value:
        return False
    return ('datocms-assets.com/130529' in value) or ('/published/assets/' in value)

img_replacements = 0
img_index = 0
for img in soup.find_all('img'):
    src = img.get('src', '')
    if is_zeekr_asset(src):
        new_src = image_srcs[img_index % len(image_srcs)]
        img['src'] = new_src
        if img.has_attr('srcset'):
            del img['srcset']
        img['alt'] = "St Catherine's School"
        img_replacements += 1
        img_index += 1

# Replace responsive <source> candidates inside the same pictures so browser does not pick old Zeekr photos.
source_replacements = 0
source_index = 0
for source in soup.find_all('source'):
    srcset = source.get('srcset', '')
    if is_zeekr_asset(srcset):
        source['srcset'] = image_srcs[source_index % len(image_srcs)]
        source_replacements += 1
        source_index += 1

# Remove Zeekr-hosted preloads for old images so they are not fetched unnecessarily.
for link in list(soup.find_all('link')):
    href = link.get('href', '')
    if is_zeekr_asset(href):
        link.decompose()

# Inject logo sizing overrides only; leave the original layout/CSS otherwise intact.
style = soup.new_tag('style')
style.string = """
/* St Catherine's asset swap: logo sizing only. */
a.logo img.stc-logo-svg,
a.logo-center img.stc-logo-svg {
  display: block;
  width: 190px;
  max-width: 42vw;
  height: auto;
}
.content-logo a.logo-center img.stc-logo-svg {
  width: 240px;
  max-width: 50vw;
}
@media (max-width: 768px) {
  a.logo img.stc-logo-svg,
  a.logo-center img.stc-logo-svg { width: 150px; max-width: 54vw; }
}
"""
(soup.head or soup).append(style)

html_path.write_text(str(soup))
print('logo_replacements', logo_replacements)
print('img_replacements', img_replacements)
print('source_replacements', source_replacements)
print('bytes', html_path.stat().st_size)
