"""Render versioned examples from reviewed training frames outside the audit reserve."""
from __future__ import annotations

import json
from pathlib import Path

from PIL import Image, ImageDraw

from pallet.annotation.workflow import is_resolved, load_jsonl
from pallet.data.protocol import file_digest, write_json


EXAMPLES = (
    ("pallet_224.png", "2023_10_7/07-10-2023_08-45-52#wood/395mm/1600mm",
     "outputs/review_round_003_small/tasks/train_047.json"),
    ("pallet_352_loaded.png", "2023_6_28/28-06-2023_01-55-01#2",
     "outputs/review_round_001/tasks/train_001.json"),
)


def render(*, labels_path, audit_groups_path, output_dir="docs/assets/annotation_policy_v4"):
    labels = load_jsonl(labels_path)
    audit_groups = set(json.loads(Path(audit_groups_path).read_text()))
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    examples = []
    for name, frame_id, task_path in EXAMPLES:
        task = json.loads(Path(task_path).read_text())
        view = next((row for row in task["frames"] if row["frame_id"] == frame_id), None)
        frame = labels.frames[frame_id]
        if (view is None or frame.split != "train" or frame.group_id in audit_groups
                or frame.group_id != view["group_id"]
                or frame.source_anchor_hash != view["source_anchor_hash"]
                or frame.status != "pos" or len(frame.boxes) != 1
                or not is_resolved(frame, require_blind=True)):
            raise ValueError(f"policy example is not an independently reviewed non-audit train frame: {frame_id}")
        source = Path(view["intensity"])
        if file_digest(source) != view["views_sha256"]["intensity.png"]:
            raise ValueError(f"example native view changed: {frame_id}")
        image = Image.open(source).convert("RGB")
        if image.size != (frame.width, frame.height):
            raise ValueError(f"example grid changed: {frame_id}")
        box = frame.boxes[0]
        xywh = [box.x, box.y, box.width, box.height]
        ImageDraw.Draw(image).rectangle((box.x, box.y, box.x + box.width,
                                         box.y + box.height), outline=(238, 66, 47), width=2)
        output = output_dir / name
        image.save(output)
        examples.append({"frame_id": frame_id, "group_id": frame.group_id,
                         "source": str(source.resolve()), "source_sha256": file_digest(source),
                         "output": str(output.resolve()), "output_sha256": file_digest(output),
                         "native_size": list(image.size), "illustrative_xywh": xywh})
    write_json(output_dir / "manifest.json", {
        "labels_sha256": file_digest(labels_path),
        "audit_groups_sha256": file_digest(audit_groups_path),
        "note": "Illustrative boxes from resolved non-audit training frames only; not validation or test references.",
        "examples": examples})
    return examples


if __name__ == "__main__":
    render(labels_path="outputs/audit_review_round_003_reblind/labels/e254577cda1b28f35285.jsonl",
           audit_groups_path="outputs/stages/pilot600_v5/audit_reserve/audit_groups.json")
