#!/usr/bin/env python3
"""Remplace les chain-images dans les recettes par des <video> autoplay/loop.
Ajoute aussi le hero atmosphère en arrière-plan.
"""
import re
from pathlib import Path

DOC = Path(__file__).parent.parent / 'particles.html'

# Mapping : slug de chain image → slug de webm
RECIPE_VIDEOS = {
    'snowstorm': 'snowstorm',
    'nebula': 'nebula',
    'bird_flock': 'flock',
    'fireworks': 'fireworks',
    'calligraphy': 'calligraphy',
    'lava': 'lava',
    'silhouette': 'dispersion',
    'constellation': 'constellation',
}


def replace_recipe_shots(html: str) -> tuple[str, list[str]]:
    """Remplace <img src="img/chains/X.png"...> par <video src="img/animations/Y.webm"...>
    dans les blocs .recipe-shot."""
    missing = []
    replaced = 0
    for chain_slug, webm_slug in RECIPE_VIDEOS.items():
        # Marker check pour idempotence
        if f'src="img/animations/{webm_slug}.webm"' in html:
            continue
        # Pattern : <img src="img/chains/SLUG.png"...>
        pattern = re.compile(
            r'<img\s+src="img/chains/' + re.escape(chain_slug) + r'\.png"[^>]*>',
            re.MULTILINE
        )
        m = pattern.search(html)
        if not m:
            missing.append(chain_slug)
            continue
        # Replace with video
        video_html = (
            f'<video src="img/animations/{webm_slug}.webm" '
            f'autoplay loop muted playsinline preload="metadata" '
            f'poster="img/chains/{chain_slug}.png" '
            f'aria-label="Recipe {chain_slug} — live particle render"></video>'
        )
        html = html[:m.start()] + video_html + html[m.end():]
        replaced += 1
    print(f'  Recipe videos: {replaced} replaced, {len(missing)} missing: {missing}')
    return html, missing


def inject_hero_video(html: str) -> str:
    """Ajoute le hero atmosphère en background du hero section."""
    if 'src="img/animations/hero.webm"' in html:
        return html
    # Cherche <div class="hero-canvas" id="heroCanvas"></div> et ajoute le video à l'intérieur
    pattern = re.compile(
        r'(<div class="hero-canvas" id="heroCanvas">)\s*(</div>)',
        re.MULTILINE
    )
    m = pattern.search(html)
    if not m:
        print('  Hero canvas not found')
        return html
    video = (
        '\n        <video class="hero-video" src="img/animations/hero.webm" '
        'autoplay loop muted playsinline preload="auto" '
        'aria-hidden="true"></video>\n    '
    )
    html = html[:m.start(2)] + video + html[m.start(2):]
    print('  Hero video: injected')
    return html


def add_css(html: str) -> str:
    """Ajoute le CSS pour <video> dans .recipe-shot + hero-video."""
    if '.recipe-shot video' in html:
        return html
    css = '''
        /* Video clips de rendu particles (recettes + hero) */
        .recipe-shot video {
            width: 100%;
            height: auto;
            display: block;
            border-radius: 6px;
        }
        .hero-video {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            opacity: 0.45;
            mix-blend-mode: screen;
            pointer-events: none;
        }
'''
    # Insère avant la dernière </style>
    idx = html.rfind('</style>')
    if idx == -1:
        print('  no </style> found')
        return html
    html = html[:idx] + css + html[idx:]
    print('  CSS injected')
    return html


def main():
    html = DOC.read_text(encoding='utf-8')
    print(f'Reading {DOC} ({len(html)} chars)')
    html = add_css(html)
    html, missing = replace_recipe_shots(html)
    html = inject_hero_video(html)
    DOC.write_text(html, encoding='utf-8')
    print(f'Wrote {DOC} ({len(html)} chars)')


if __name__ == '__main__':
    main()
