"""Rewrite insta_mapping.json image_urls from Discord CDN → server PC URLs.

For each entry, look at local insta_photos/{thread_id}/ for downloaded files
and emit https://fearx-photos.sbxg.win/insta/{thread_id}/{filename} URLs.
"""
import json
import sys
from pathlib import Path

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

HERE = Path(__file__).resolve().parent
MAPPING = HERE / 'insta_mapping.json'
PHOTOS = HERE / 'insta_photos'
BASE_URL = 'https://fearx-photos.sbxg.win/insta'


VIDEO_EXTS = ('.mp4', '.mov', '.webm', '.m4v')


def main():
    # Rebuild mapping from insta_meta.json so we get video_urls in it.
    META = HERE / 'insta_meta.json'
    if META.is_file():
        # Bootstrap mapping with video_urls field by re-running the build script logic.
        # Simpler: read the updated insta_meta directly and run mapping builder again.
        import subprocess
        subprocess.run(['python', 'build_insta_mapping.py'], cwd=str(HERE), check=False)
    mapping = json.loads(MAPPING.read_text(encoding='utf-8'))
    rewrites = 0
    misses = 0
    for week, days in mapping.items():
        for day, slots in days.items():
            for slot in ('lunch', 'dinner', 'extra'):
                for entry in (slots.get(slot) or []):
                    tid = entry.get('thread_id')
                    if not tid:
                        continue
                    local_dir = PHOTOS / tid
                    if not local_dir.is_dir():
                        misses += 1
                        continue
                    files = sorted(local_dir.iterdir())
                    image_urls = []
                    video_urls = []
                    for f in files:
                        if not f.is_file():
                            continue
                        url = f'{BASE_URL}/{tid}/{f.name}'
                        if f.suffix.lower() in VIDEO_EXTS:
                            video_urls.append(url)
                        else:
                            image_urls.append(url)
                    if image_urls or video_urls:
                        entry['image_urls_discord'] = entry.get('image_urls') or []
                        entry['image_urls'] = image_urls
                        entry['video_urls'] = video_urls
                        rewrites += 1
    MAPPING.write_text(json.dumps(mapping, ensure_ascii=False, indent=2), encoding='utf-8')
    print(f'rewrites: {rewrites}, misses: {misses}')


if __name__ == '__main__':
    main()
