#!/usr/bin/env python3
"""把 260630 的 comps.html 改回 fetch 加载 media.json，并加入 BASE_PATH 解析。"""
import re
from pathlib import Path

STAGING = Path(__file__).parent.resolve() / "vps_staging"
HTML = STAGING / "comps.html"

FETCH_SCRIPT = r'''  <script>
    const PREVIEW_COUNT = 6;
    const BASE_PATH = location.pathname.replace(/\/[^\/]*$/, '');
    function resolve(p) { return p.startsWith('/') ? p : (BASE_PATH + '/' + p); }

    function imgTag(thumb, full) {
      return `<img src="${resolve(thumb)}" loading="lazy" alt="" onclick="openLightbox('${resolve(full)}')">`;
    }

    function videoTag(src) {
      return `<video src="${resolve(src)}" controls preload="metadata"></video>`;
    }

    async function loadMedia() {
      let data = {};
      try {
        const res = await fetch(resolve('media.json'));
        if (!res.ok) throw new Error('media.json ' + res.status);
        data = await res.json();
      } catch (e) {
        console.error('加载 media.json 失败', e);
      }

      document.querySelectorAll('.media-gallery').forEach(el => {
        const slug = el.dataset.slug;
        const media = data[slug] || {};
        const images = media.images || [];
        const thumbnails = media.thumbnails || images;
        const videos = media.videos || [];

        if (images.length === 0 && videos.length === 0) {
          el.innerHTML = '<p class="placeholder">暂无照片/视频</p>';
          return;
        }

        const pairs = images.map((src, i) => [thumbnails[i] || src, src]);
        let html = '';

        html += '<div class="gallery gallery-preview">';
        pairs.slice(0, PREVIEW_COUNT).forEach(([thumb, full]) => { html += imgTag(thumb, full); });
        html += '</div>';

        if (pairs.length > PREVIEW_COUNT) {
          html += '<div class="gallery gallery-more">';
          pairs.slice(PREVIEW_COUNT).forEach(([thumb, full]) => { html += imgTag(thumb, full); });
          html += '</div>';
          html += `<button class="gallery-toggle" onclick="toggleGallery(this)">显示剩余 ${pairs.length - PREVIEW_COUNT} 张照片</button>`;
        }

        if (videos.length) {
          html += '<div class="gallery gallery-videos">';
          videos.forEach(src => { html += videoTag(src); });
          html += '</div>';
        }

        el.innerHTML = html;
      });
    }

    function toggleGallery(btn) {
      const more = btn.previousElementSibling;
      more.classList.toggle('visible');
      const remaining = more.querySelectorAll('img').length;
      btn.textContent = more.classList.contains('visible')
        ? '收起照片'
        : `显示剩余 ${remaining} 张照片`;
    }

    function openLightbox(src) {
      const box = document.getElementById('lightbox');
      document.getElementById('lightbox-img').src = src;
      box.classList.add('active');
    }

    document.querySelectorAll('tbody tr[data-href]').forEach(row => {
      row.addEventListener('click', () => {
        location.hash = row.dataset.href;
      });
    });

    loadMedia();
  </script>'''


def main():
    html = HTML.read_text(encoding="utf-8")

    # 把带内容的 media-gallery 恢复为空容器
    html = re.sub(
        r'<div class="media-gallery" data-slug="([^"]+)">[\s\S]*?</div>\s*</section>',
        r'<div class="media-gallery" data-slug="\1"></div>\n        </section>',
        html,
    )

    # 替换 script 块
    html = re.sub(r'  <script>[\s\S]*?</script>', FETCH_SCRIPT, html, count=1)

    HTML.write_text(html, encoding="utf-8")
    print(f"已更新 {HTML}")


if __name__ == "__main__":
    main()
