#!/usr/bin/env python3
"""Mask only the pairing-token field while the pairing heading is visible.
Usage: redact-pairing.py heading-template.png input.webm output.mp4
The heading template contains only public UI text, never the token.
"""
import json
import subprocess
import sys
from fractions import Fraction
from PIL import Image, ImageChops, ImageStat

template_path, source, destination = sys.argv[1:]
metadata = json.loads(subprocess.check_output([
    "ffprobe", "-v", "error", "-select_streams", "v:0",
    "-show_entries", "stream=width,height,avg_frame_rate", "-of", "json", source,
]))["streams"][0]
if (metadata["width"], metadata["height"]) != (1280, 800):
    raise SystemExit("Expected the recorded 1280x800 viewport")
fps = float(Fraction(metadata["avg_frame_rate"]))
width, height = 300, 26
reference = Image.open(template_path).convert("L")
raw = subprocess.check_output([
    "ffmpeg", "-hide_banner", "-loglevel", "error", "-i", source,
    "-vf", "crop=300:26:375:294:exact=1,format=rgb24", "-f", "rawvideo", "-",
])
frame_size = width * height * 3
matches = []
for index in range(len(raw) // frame_size):
    frame = Image.frombytes("RGB", (width, height), raw[index * frame_size:(index + 1) * frame_size]).convert("L")
    if ImageStat.Stat(ImageChops.difference(reference, frame)).mean[0] < 6:
        matches.append(index / fps)
intervals = []
for timestamp in matches:
    start, end = max(0, timestamp - .25), timestamp + 1 / fps + .25
    if intervals and start <= intervals[-1][1]:
        intervals[-1][1] = max(intervals[-1][1], end)
    else:
        intervals.append([start, end])
filters = []
if intervals:
    enable = "+".join(f"between(t,{start:.3f},{end:.3f})" for start, end in intervals)
    filters = ["-vf", f"drawbox=x=375:y=394:w=530:h=34:color=black:t=fill:enable='{enable}',drawtext=text='Dev pairing token redacted':x=385:y=403:fontsize=14:fontcolor=white:enable='{enable}'"]
subprocess.run([
    "ffmpeg", "-hide_banner", "-loglevel", "error", "-i", source, *filters,
    "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-threads", "2",
    "-an", "-movflags", "+faststart", destination,
], check=True)
print(json.dumps({"redactedIntervalsSeconds": intervals, "matchedFrames": len(matches)}))
