"""Add a clearly separated DOM observation footer to the raw app screenshots.
Usage: python3 annotate-evidence.py PROOF_JSON OBSERVATIONS_DIR OUTPUT_DIR
The app pixels are copied unchanged; the footer is evidence metadata, not app UI.
"""
import json
import pathlib
import sys
from PIL import Image, ImageDraw, ImageFont

proof = json.loads(pathlib.Path(sys.argv[1]).read_text())
observations = sorted(pathlib.Path(sys.argv[2]).glob('*-observed-links.json'))[-2:]
output = pathlib.Path(sys.argv[3])
font = ImageFont.truetype('DejaVuSansMono.ttf', 17)
for side, observation_path in zip(['base', 'head'], observations):
    record = json.loads(observation_path.read_text())
    assert record['identity']['canonicalKey'] == 'altssh.gitlab.com/group/project'
    assert record['identity']['webUrl'] is None
    source = next(p for p in proof[side]['captures'] if p.endswith('004-gitlab-merge-request-fallback.png'))
    image = Image.open(source).convert('RGB')
    result = Image.new('RGB', (image.width, image.height + 120), '#f4f5f7')
    result.paste(image, (0, 0))
    draw = ImageDraw.Draw(result)
    draw.line((0, image.height, image.width, image.height), fill='#808080', width=2)
    y = image.height + 14
    for line in [
        f"{'BEFORE' if side == 'base' else 'AFTER'} | client {proof[side]['sha'][:10]} | legacy server 84fe59bb3b | 1280x800, light",
        "Annotation outside app: observed href of the 'Open on GitLab' link",
        record['mergeRequestUrl'],
        "Server identity: altssh.gitlab.com/group/project | webUrl: absent",
    ]:
        draw.text((18, y), line, font=font, fill='#151515')
        y += 25
    result.save(output / f'{side}-merge-request-fallback-observed-href.png')
    (output / f'{side}-observed-links.json').write_text(json.dumps(record, indent=2) + '\n')
