from pathlib import Path
from PIL import Image, ImageDraw
import zipfile, subprocess
ROOT = Path(__file__).parent
for side, sha in [('base', '2c4310eb06'), ('head', '3f77e41224')]:
    source = ROOT / f'{side}-final'
    source.mkdir(exist_ok=True)
    with zipfile.ZipFile(ROOT / f'{side}-final.zip') as archive:
        for info in archive.infolist():
            output = source / info.filename.replace('\\', '/')
            if info.is_dir():
                output.mkdir(parents=True, exist_ok=True)
            else:
                output.parent.mkdir(parents=True, exist_ok=True)
                output.write_bytes(archive.read(info))
    frames = source / 'frames'
    processed = ROOT / f'{side}-private-details-masked'
    processed.mkdir(exist_ok=True)
    for frame in sorted(frames.glob('*.jpg')):
        image = Image.open(frame).convert('RGB')
        draw = ImageDraw.Draw(image)
        if side == 'head':
            dark = sum(max(pixel) < 90 for pixel in image.crop((596,251,845,272)).getdata())
            if dark > 200:
                draw.rectangle((665,284,718,305), fill='#555555')
        else:
            # The recovery footer contains the scratch data directory.
            draw.rectangle((674,680,1255,728), fill='#555555')
        image.save(processed / (frame.stem + '.png'))
    label = f'{"Before" if side == "base" else "After"} - {sha} - Windows Server 2025 - 1920x1080'
    filters = f"drawbox=x=0:y=0:w=iw:h=32:color=black:t=fill,drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='{label}':x=12:y=5:fontsize=19:fontcolor=white,drawbox=x=0:y=1030:w=iw:h=50:color=black:t=fill,drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='Elapsed %{{pts\\:hms}} - real-time playback, captured at 2 fps':x=12:y=1044:fontsize=18:fontcolor=white"
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-framerate','2','-i',str(processed/'%04d.png'),'-vf',filters,'-c:v','libx264','-preset','fast','-crf','18','-r','30','-pix_fmt','yuv420p','-movflags','+faststart',str(ROOT/f'{side}-startup.mp4')],check=True)
    a=(source/'app-window-60.png').read_bytes()
    b=(source/'app-window-61.png').read_bytes()
    if a != b: raise RuntimeError(f'{side} app-window still is not stable over the 500ms pair')
    image=Image.open(source/'app-window-61.png').convert('RGB')
    if side=='base':
        image=image.crop((0,0,image.width,round(image.height*0.84)))
        image.resize((900,round(image.height*900/image.width))).save(ROOT/'before-recovery.png')
    else:
        # Window thumbnails are scaled from the 1100x780 native window.
        draw=ImageDraw.Draw(image)
        draw.rectangle((round(image.width*0.231),round(image.height*0.200),round(image.width*0.285),round(image.height*0.231)),fill='#555555')
        image.resize((1100,780)).save(ROOT/'after-welcome.png')
