"""capture_html.py - turn an animated HTML file (e.g. made by Claude) into a smooth MP4, frame by frame.
Free from AI Tools Dock: https://www.aitoolsdock.com/free/claude-animation-kit.html  (MIT licence)

Needs: Python 3.9+, Google Chrome, and  pip install imageio-ffmpeg
It opens the page in headless Chrome once per frame, jumps to that exact time, saves a screenshot,
then stitches all frames into an MP4 (no screen recording, no dropped frames).

Modes (pick the one that matches how the animation was built):
  CSS animations (default)    every CSS animation is paused at time t
  --renderat                  calls window.renderAt(t) (Three.js / canvas pages built to be deterministic)

Examples:
  python capture_html.py short.html short.mp4 --end 30                     # 9:16, 1080x1920, 30 fps
  python capture_html.py intro.html intro.mp4 --end 6 --size 1920,1080     # 16:9
  python capture_html.py moon.html moon.mp4 --end 30 --renderat
  # Stretch scenes to match a longer voiceover: [[out_start, out_len, anim_start, anim_len], ...]
  python capture_html.py short.html short.mp4 --end 39.5 --timemap "[[0,4,0,4],[4,9.1,4,6]]"
Add the voiceover afterwards in any editor (or with ffmpeg).
"""
import argparse
import concurrent.futures as cf
import json
import re
import subprocess
import time
from pathlib import Path

import imageio_ffmpeg

import os
import sys

# Path to Google Chrome. Set the CHROME environment variable if yours is somewhere else.
CHROME = os.environ.get("CHROME") or {
    "win32": r"C:\Program Files\Google\Chrome\Application\chrome.exe",
    "darwin": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
}.get(sys.platform, "google-chrome")

HEAD = "<script>window.requestAnimationFrame=function(){return 0};</script>"
SEEK = """<script>
(function(){
  var STARTS=%s, END=%s, WIPE=0.9;
  var t=parseFloat((location.hash||'#0').slice(1))||0;
  var scenes=[].slice.call(document.querySelectorAll('.scene'));
  var i=0; for(var k=0;k<STARTS.length;k++) if(t>=STARTS[k]) i=k;
  scenes.forEach(function(s){s.classList.remove('on','enter','top');});
  if(i>0 && t-STARTS[i]<WIPE) scenes[i-1].classList.add('on','enter');
  void document.body.offsetWidth;
  scenes[i].classList.add('on','enter','top');
  var fills=document.querySelectorAll('#bar i');
  [].forEach.call(fills,function(f,j){var a=STARTS[j],b=STARTS[j+1]||END;
    f.style.transform='scaleX('+Math.max(0,Math.min(1,(t-a)/(b-a)))+')';});
  document.getAnimations().forEach(function(a){
    var el=a.effect&&a.effect.target, sc=el&&el.closest&&el.closest('.scene');
    var j=sc?scenes.indexOf(sc):i;
    a.pause(); a.currentTime=Math.max(0,(t-STARTS[j])*1000);
  });
})();
</script>"""


SIMPLE = """<script>
(function(){
  var t=parseFloat((location.hash||'#0').slice(1))||0;
  document.getAnimations().forEach(function(a){a.pause(); a.currentTime=t*1000;});
})();
</script>"""


RENDERAT = """<script>
(function(){
  var t=parseFloat((location.hash||'#0').slice(1))||0, n=0;
  var iv=setInterval(function(){
    if(typeof window.renderAt==='function'){ clearInterval(iv); window.renderAt(t); window.renderAt(t); }
    else if(++n>400) clearInterval(iv);
  },10);
})();
</script>"""


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("html"); ap.add_argument("out")
    ap.add_argument("--starts", default=""); ap.add_argument("--end", type=float, required=True)
    ap.add_argument("--size", default="1080,1920")
    ap.add_argument("--timemap", default="", help="json [[out_start, out_len, anim_start, anim_len], ...] to stretch scenes")
    ap.add_argument("--tag", default="")
    ap.add_argument("--renderat", action="store_true", help="page exposes window.renderAt(seconds)")
    ap.add_argument("--budget", type=int, default=1500, help="ms of virtual time per frame")
    ap.add_argument("--query", default="", help="query string for the page, e.g. record")
    ap.add_argument("--fps", type=int, default=30); ap.add_argument("--jobs", type=int, default=6)
    a = ap.parse_args()
    src = Path(a.html).resolve()
    html = src.read_text(encoding="utf-8")
    if a.renderat:
        tail = RENDERAT
    else:
        tail = SEEK % ("[" + a.starts + "]", a.end) if a.starts else SIMPLE
        html = html.replace("<head>", "<head>" + HEAD, 1)
    html = re.sub(r"</body>", tail + "</body>", html, count=1)
    w, h = a.size.split(",")
    seek = src.with_name(src.stem + "_seek.html")
    seek.write_text(html, encoding="utf-8")
    frames = src.parent / (src.stem + "_frames" + a.tag)
    frames.mkdir(exist_ok=True)
    n = int(a.end * a.fps)
    tmap = json.loads(a.timemap) if a.timemap else None

    def anim_t(t):
        if not tmap:
            return t
        for os_, ol, as_, al in tmap:
            if t < os_ + ol:
                return as_ + max(0.0, t - os_) * al / ol
        os_, ol, as_, al = tmap[-1]
        return as_ + al

    def shot(k):
        out = frames / f"f{k:04d}.png"
        if out.exists() and out.stat().st_size > 1000:
            return
        url = seek.as_uri() + (("?" + a.query) if a.query else "") + f"#{anim_t(k / a.fps):.4f}"
        try:
            _run(out, url)
        except subprocess.TimeoutExpired:
            pass  # retried by the missing-frame loop

    def _run(out, url):
        k = int(out.stem[1:])
        gl = ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] if a.renderat else ["--disable-gpu"]
        subprocess.run([CHROME, "--headless=new", *gl, "--hide-scrollbars", "--force-device-scale-factor=1",
                        f"--user-data-dir={frames / ('prof%d' % (k % a.jobs))}", f"--window-size={w},{h}",
                        f"--virtual-time-budget={a.budget}", f"--screenshot={out}", url],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60)

    for _ in range(4):  # chrome sometimes exits before writing; retry the missing frames
        missing = [k for k in range(n) if not (frames / f"f{k:04d}.png").exists()]
        if not missing:
            break
        with cf.ThreadPoolExecutor(a.jobs) as ex:
            list(ex.map(shot, missing))
        time.sleep(3)
    ff = imageio_ffmpeg.get_ffmpeg_exe()
    subprocess.run([ff, "-y", "-loglevel", "error", "-framerate", str(a.fps), "-i", str(frames / "f%04d.png"),
                    "-vf", f"scale={w}:{h},format=yuv420p", "-c:v", "libx264", "-crf", "18", a.out], check=True)
    print(a.out, n, "frames")


if __name__ == "__main__":
    main()
