#!/usr/bin/env python3
"""Check whether two judgments of one image become two COCO image IDs."""

import ast
from collections import defaultdict
from contextlib import nullcontext, redirect_stdout
from hashlib import sha256
import io
import json
import os
from pathlib import Path
import runpy
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from urllib.request import urlopen


BASE_CHECK = "d0c07cc9d456ff7aac992cc11340094d4e477e071e57ab06ce2431d95595f09f"
COCO_SOURCE = (
    "https://raw.githubusercontent.com/ppwwyyxx/cocoapi/"
    "2971b0430e0990f119c60c8708ca66d4a5fed5d0/PythonAPI/pycocotools/coco.py"
)
COCO_SHA = "4a234fc502c6e622f044747312d6a696652545f527e766c98bedf5aa4ca77f41"


def load_coco_index(select_functions):
    with urlopen(COCO_SOURCE, timeout=12) as response:
        raw = response.read(18_977)
    if len(raw) != 18_976 or sha256(raw).hexdigest() != COCO_SHA:
        raise ValueError("Pinned COCO index source changed")
    tree = ast.parse(raw, filename="coco.py")
    index_class, = (node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "COCO")
    index_class.body = select_functions(index_class.body, {"createIndex", "getImgIds"})
    functions = select_functions(tree.body, {"_isArrayLike"})
    namespace = {"defaultdict": defaultdict}
    module = ast.Module(body=functions + [index_class], type_ignores=[])
    exec(compile(module, "pinned-coco-index-slice", "exec"), namespace)
    return namespace["COCO"]


def converter_for(fixture, image):
    base = fixture["load_converter"]()
    read_source = fixture["read_source"]
    select = fixture["select_functions"]
    source = read_source("converter.py")
    converter, = (node for node in source.body if isinstance(node, ast.ClassDef) and node.name == "Converter")
    converter.body = select(converter.body, {"convert_to_coco", "rotated_rectangle"})
    converter.name = "CocoConverter"
    converter.bases = [ast.Name(id="Converter", ctx=ast.Load())]
    helper = select(read_source("keypoints.py").body, {"update_categories_for_keypoints"})

    def open_local_image(path):
        if Path(path) != image:
            raise ValueError("Unexpected fixture image path")
        return nullcontext(SimpleNamespace(size=(100, 100)))

    namespace = base.convert_to_yolo.__func__.__globals__
    namespace["Format"].COCO = "COCO"
    namespace["Image"] = SimpleNamespace(open=open_local_image)
    module = ast.fix_missing_locations(ast.Module(body=helper + [converter], type_ignores=[]))
    exec(compile(module, "pinned-coco-export-slice", "exec"), namespace)
    instance = namespace["CocoConverter"]()
    instance._schema = base._schema
    instance._data_keys = base._data_keys
    instance.is_keypoints = False
    return instance


def export(converter, index_type, image, folder, judgments):
    folder.mkdir()
    task = folder / "task.json"
    task.write_text(json.dumps({"id": 7, "data": {"image": str(image)}, "annotations": judgments}))
    converter.convert_to_coco(str(task), str(folder / "coco"), is_dir=False)
    result = json.loads((folder / "coco" / "result.json").read_bytes())
    if not result["images"] or any(row["file_name"] != str(image) for row in result["images"]):
        raise ValueError("The converter altered the shared image path")
    index = index_type()
    index.dataset = result
    with redirect_stdout(io.StringIO()):
        index.createIndex()
    category_names = {category["id"]: category["name"] for category in result["categories"]}
    return {
        "source_judgment_ids": [entry["id"] for entry in judgments],
        "exported_images": [{**row, "file_name": image.name} for row in result["images"]],
        "exported_annotations": [
            {**row, "category_name": category_names[row["category_id"]]}
            for row in result["annotations"]
        ],
        "indexed_image_ids": index.getImgIds(),
        "indexed_annotation_ids_by_image": {
            str(image_id): [entry["id"] for entry in index.imgToAnns[image_id]]
            for image_id in index.getImgIds()
        },
    }


def main():
    base = Path(__file__).resolve().with_name("check.py")
    if sha256(base.read_bytes()).hexdigest() != BASE_CHECK:
        raise ValueError("The reviewed base checker changed")
    fixture = runpy.run_path(str(base))
    index_type = load_coco_index(fixture["select_functions"])
    annotation = fixture["annotation"]
    a = annotation(101, 11, 1, "A")
    b = annotation(102, 12, 2, "B")
    second_a = annotation(102, 12, 2, "A")
    os.environ.pop("LABEL_STUDIO_FORCE_ANNOTATOR_EXPORT", None)
    results = {}
    with TemporaryDirectory(prefix="sapien1-coco-identity-") as temporary:
        root = Path(temporary)
        image = root / "sample.pgm"
        image.write_bytes(b"P5\n100 100\n255\n" + bytes(10_000))
        converter = converter_for(fixture, image)
        for name, judgments, classes in (
            ("same_image_disagreement", [a, b], ["B", "A"]),
            ("same_image_agreement", [a, second_a], ["A", "A"]),
            ("one_selected_judgment", [a], ["A"]),
        ):
            result = export(converter, index_type, image, root / name, judgments)
            expected_ids = list(range(len(classes)))
            if (
                [row["id"] for row in result["exported_images"]] != expected_ids
                or result["indexed_image_ids"] != expected_ids
                or [row["image_id"] for row in result["exported_annotations"]] != expected_ids
                or [row["category_name"] for row in result["exported_annotations"]] != classes
                or any("annotator" in row for row in result["exported_annotations"])
            ):
                raise ValueError(f"COCO identity result changed in {name}")
            results[name] = result
    print(json.dumps({
        "sdk_revision": fixture["REVISION"],
        "base_checker_sha256": BASE_CHECK,
        "coco_index_source_sha256": COCO_SHA,
        "cases": results,
    }, indent=2))


if __name__ == "__main__":
    main()
