"""Route illustrated audit frames for new reviewers without example overlays."""
from __future__ import annotations

import argparse
from copy import deepcopy
import json
from pathlib import Path

from pallet.data.protocol import file_digest, write_json


def prepare(tasks, policy_manifest, output):
    tasks = Path(tasks)
    manifest = json.loads(Path(policy_manifest).read_text())
    example_hashes = {entry["source_sha256"] for entry in manifest["examples"]}
    frames = []
    protocol_hashes = set()
    for task_path in sorted(tasks.glob("*.json")):
        task = json.loads(task_path.read_text())
        protocol_hashes.add(task["protocol_sha256"])
        for frame in task["frames"]:
            if frame["views_sha256"]["intensity.png"] in example_hashes:
                frames.append(deepcopy(frame))
    if len(protocol_hashes) != 1 or len(frames) != len(example_hashes):
        raise ValueError("cannot uniquely locate each illustrated audit frame")
    for index, frame in enumerate(frames):
        frame["index"] = index
    output = Path(output)
    write_json(output / "tasks" / "train_000.json", {
        "task_id": "train_000", "protocol_sha256": next(iter(protocol_hashes)),
        "instructions": "Independent re-review using original views only. Do not open annotation-policy pictures, historical reviews or model predictions. Pallet box starts at its visible deck and ends at its lowest visible foot/runner; exclude cargo, ground, fork tines and fixed racks. Native xywh. Ambiguous identity => ignore.",
        "frames": frames})
    original_cache = json.loads((tasks.parent / "cache_index.json").read_text())
    write_json(output / "cache_index.json", {frame["frame_id"]: original_cache[frame["frame_id"]]
                                               for frame in frames})
    write_json(output / "manifest.json", {
        "policy_manifest_sha256": file_digest(policy_manifest),
        "frame_ids": [frame["frame_id"] for frame in frames],
        "reason": "Prior audit reviewers could see illustrative boxes for these exact frames. Independent replacement opinions must not view the examples."})
    return {"frames": len(frames), "output": str(output)}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--tasks", default="outputs/audit_review_round_003_small/tasks")
    parser.add_argument("--policy-manifest", default="docs/assets/annotation_policy_v3/manifest.json")
    parser.add_argument("--output", default="outputs/audit_review_round_003_reblind")
    args = parser.parse_args()
    print(json.dumps(prepare(args.tasks, args.policy_manifest, args.output)))
