import json

import pytest
from PIL import Image

from pallet.annotation import (
    AnnotationSet, Box, FrameAnnotation, Provenance, Review, SceneAttributes,
    annotation_digest, create_proposals, export_audit, export_coco, export_yolo,
    is_resolved, load_jsonl, merge_proposals, record_review, reference_eligible,
    save_jsonl, seal_splits,
)


def test_train_review_can_use_proposal_but_test_review_must_be_blind():
    train = FrameAnnotation("train/f", "g1", "image.png", 32, 32, split="train")
    record_review(train, Review("r1", "approve", blind=False),
                  status="pos", boxes=[Box(1, 1, 5, 5)])
    assert train.status == "pos"
    test = FrameAnnotation("test/f", "g2", "image.png", 32, 32, split="test")
    with pytest.raises(ValueError, match="must be blind"):
        record_review(test, Review("r2", "approve", blind=False))


def frame(fid="batch/1", group="batch/1", domain="dock", split=None):
    return FrameAnnotation(fid, group, f"{fid}.png", 100, 80, domain=domain, split=split,
                           source_anchor_hash="source-digest")


def test_round_trip_proposals_review_and_exports(tmp_path):
    ds = AnnotationSet([frame()])
    box = Box(10, 20, 30, 20)
    merge_proposals(ds, {"batch/1": [box]}, provenance=Provenance("sam3", model="sam3"))
    assert ds.frames["batch/1"].status == "unreviewed"  # proposal is not a label
    record_review(ds.frames["batch/1"], Review("reviewer-a", "approve"),
                  status="pos", boxes=[box], scene=SceneAttributes(lighting="dim"))
    path = tmp_path / "labels.jsonl"
    save_jsonl(ds, path)
    loaded = load_jsonl(path)
    assert loaded.frames["batch/1"].boxes == [box]
    assert loaded.frames["batch/1"].scene.lighting == "dim"
    coco = export_coco(loaded)
    assert coco["categories"] == [{"id": 1, "name": "pallet", "supercategory": "object"}]
    assert coco["annotations"] == []
    assert loaded.unresolved()  # second independent review is still pending
    record_review(loaded.frames["batch/1"], Review("reviewer-b", "approve"))
    assert loaded.unresolved() == []
    assert export_coco(loaded)["annotations"][0]["bbox"] == [10, 20, 30, 20]
    labels = export_yolo(loaded, tmp_path / "yolo")
    assert labels[0].read_text().startswith("0 0.25000000 0.37500000")
    assert json.loads((tmp_path / "yolo" / "batch__1.json").read_text())["status"] == "pos"


def test_negative_and_ignore_are_explicit_and_positive_needs_boxes():
    negative = frame("a", "a")
    negative.status = "negative"
    negative.validate()
    with pytest.raises(ValueError):
        FrameAnnotation("b", "b", "b.png", 10, 10, status="pos").validate()
    ds = AnnotationSet([negative, frame("b", "b")])
    report = ds.qa()
    assert report["status_counts"]["negative"] == 1
    assert report["unresolved"] == 2


def test_test_detector_proposals_rejected_after_serialization_and_same_domain_split_allowed(tmp_path):
    test_frame = frame("test/1", "test-group", domain="dock", split="test")
    train_frame = frame("train/1", "train-group", domain="dock")
    ds = AnnotationSet([test_frame, train_frame])
    path = tmp_path / "sealed.jsonl"
    save_jsonl(ds, path)
    ds = load_jsonl(path)
    with pytest.raises(ValueError, match="blind validation/test"):
        merge_proposals(ds, {"test/1": [Box(1, 1, 2, 2)]},
                        provenance=Provenance("detector", trained_group_ids=("train-group",)))
    with pytest.raises(ValueError, match="trained on sealed test"):
        merge_proposals(ds, {}, provenance=Provenance("detector", trained_group_ids=("test-group",)))
    # Sensor configuration/domain can occur in all partitions; frame groups are
    # the isolation boundary.
    seal_splits(ds, {"test-group": "test", "train-group": "train"})
    with pytest.raises(ValueError, match="already sealed"):
        seal_splits(ds, {"test-group": "train", "train-group": "train"})


def test_split_seal_groups_together_and_reviewers_distinct():
    ds = AnnotationSet([frame("v1", "g1", "site-a"), frame("v2", "g1", "site-a"),
                        frame("v3", "g2", "site-b")])
    seal_splits(ds, {"g1": "train", "g2": "test"})
    assert {f.split for f in ds.frames.values() if f.group_id == "g1"} == {"train"}
    f = ds.frames["v1"]
    record_review(f, Review("r1", "approve"), status="negative")
    with pytest.raises(ValueError, match="independent"):
        record_review(f, Review("r1", "approve"))


def test_coco_defaults_to_resolved_and_audit_preserves_metadata(tmp_path):
    negative = frame("negative", "g1")
    record_review(negative, Review("r1", "approve"), status="negative")
    record_review(negative, Review("r2", "approve"))
    ignored = frame("ignore", "g2")
    ignored.status = "ignore"
    pending = frame("pending", "g3")
    ds = AnnotationSet([negative, ignored, pending])
    coco = export_coco(ds)
    assert [(im["frame_id"], im["status"]) for im in coco["images"]] == [
        ("negative", "negative")]
    assert [im["frame_id"] for im in export_audit(ds)["images"]] == [
        "ignore", "negative", "pending"]
    paths = export_yolo(ds, tmp_path / "yolo")
    assert [p.name for p in paths] == ["negative.txt"]
    assert paths[0].read_text() == ""


def test_review_digest_rejects_final_payload_mutation_and_legacy_reviews(tmp_path):
    item = frame("bound", "g")
    box = Box(1, 2, 3, 4)
    record_review(item, Review("a", "approve"), status="pos", boxes=[box])
    record_review(item, Review("b", "approve"))
    assert is_resolved(item)
    before = annotation_digest(item)
    item.boxes = [Box(2, 2, 3, 4)]
    assert annotation_digest(item) != before
    assert not is_resolved(item)
    record_review(item, Review("a", "approve"))
    record_review(item, Review("b", "approve"))
    assert is_resolved(item) and len(item.reviews) == 4
    item.boxes = [box]
    item.scene = SceneAttributes(tags=("occluded",))
    assert not is_resolved(item)
    legacy = frame("legacy", "g")
    legacy.status, legacy.boxes = "pos", [box]
    legacy.reviews = [Review("a", "approve"), Review("b", "approve")]
    path = tmp_path / "legacy.jsonl"
    save_jsonl(AnnotationSet([legacy]), path)
    assert not is_resolved(load_jsonl(path).frames["legacy"])


def test_failed_review_does_not_mutate_frame():
    item = frame("atomic", "g")
    with pytest.raises(ValueError, match="positive frame"):
        record_review(item, Review("a", "approve"), status="pos")
    assert item.status == "unreviewed" and item.reviews == [] and item.boxes == []
    with pytest.raises(ValueError, match="differ"):
        record_review(item, Review("a", "approve", boxes=(Box(2, 2, 2, 2),)),
                      status="pos", boxes=[Box(1, 1, 2, 2)])
    assert item.status == "unreviewed" and item.reviews == []


def test_structured_adjudication_requires_two_independent_proposals():
    item = frame("dispute", "g")
    proposed_a, proposed_b = Box(1, 1, 5, 5), Box(2, 1, 5, 5)
    record_review(item, Review("a", "needs_work", status="pos", boxes=(proposed_a,)))
    id_a = item.reviews[-1].review_id
    record_review(item, Review("b", "needs_work", status="pos", boxes=(proposed_b,)))
    id_b = item.reviews[-1].review_id
    record_review(item, Review("arbiter", "adjudicate", adjudicates=(id_a, id_b)),
                  status="pos", boxes=[proposed_a])
    assert is_resolved(item)
    item.boxes = [proposed_b]
    assert not is_resolved(item)
    item.boxes = [proposed_a]
    item.reviews[-1] = Review("arbiter", "adjudicate", annotation_digest=annotation_digest(item),
                              status="pos", boxes=(proposed_a,), adjudicates=(id_a, "unknown"))
    assert not is_resolved(item)


def test_blind_reference_rejected_after_split_reassignment():
    item = frame("assisted", "g", split="train")
    item.provenance.append(Provenance("fewshot", actor="model"))
    box = Box(1, 1, 5, 5)
    record_review(item, Review("a", "approve", blind=False), status="pos", boxes=[box])
    record_review(item, Review("b", "approve", blind=False))
    assert is_resolved(item)
    item.split = "test"
    assert not reference_eligible(item)
    assert not is_resolved(item, require_blind=True)
    assert export_coco(AnnotationSet([item]))["images"] == []


def test_create_proposals_marks_pcd_only_dimensions_pending():
    class Record:
        frame_id = "pcd/1"
        group_id = "pcd/1"
        paths = {"pcd": "/source/frame.pcd"}
    ds = create_proposals([Record()])
    item = ds.frames["pcd/1"]
    assert item.image == "/source/frame.pcd"
    assert item.dimensions_pending
    assert "visualization dimensions are pending" in ds.qa()["problems"][0]


def test_create_proposals_infers_sensor_image_dimensions(tmp_path):
    image_path = tmp_path / "depth.png"
    Image.new("I;16", (640, 480)).save(image_path)
    class Record:
        frame_id = "sensor/1"
        group_id = "sensor/1"
        paths = {"depth": image_path}
    ds = create_proposals([Record()])
    item = ds.frames["sensor/1"]
    assert (item.width, item.height) == (640, 480)
    assert not item.dimensions_pending


def test_create_proposals_uses_pcd_anchor_without_registration_proof(tmp_path):
    pcd_path = tmp_path / "cloud.pcd"
    pcd_path.write_text(
        "# .PCD v0.7\nVERSION .7\nFIELDS x y z\nSIZE 4 4 4\nTYPE F F F\n"
        "COUNT 1 1 1\nWIDTH 307200\nHEIGHT 1\nPOINTS 307200\nDATA ascii\n"
    )
    depth_path = tmp_path / "depth.png"
    rgb_path = tmp_path / "rgb.jpg"
    Image.new("I;16", (640, 480)).save(depth_path)
    Image.new("RGB", (1280, 960)).save(rgb_path)
    class Record:
        frame_id = "registered/1"
        group_id = "registered/1"
        paths = {"pcd": pcd_path, "depth": depth_path, "rgb": rgb_path}
    item = create_proposals([Record()]).frames["registered/1"]
    assert item.image == str(pcd_path)
    assert (item.width, item.height) == (640, 480)
    assert item.evidence_images == [str(rgb_path), str(depth_path)]


def test_create_proposals_reuses_verified_pcd_hash_and_registered_raster(tmp_path):
    pcd_path = tmp_path / "cloud.pcd"
    pcd_path.write_text("WIDTH 2\nHEIGHT 2\nPOINTS 4\nDATA ascii\n0 0 0\n")
    depth_path = tmp_path / "depth.png"
    Image.new("I;16", (2, 2)).save(depth_path)

    class Record:
        frame_id = "registered/2"
        group_id = "registered/2"
        paths = {"pcd": pcd_path, "depth": depth_path}
        sensor_config = {"rasters_aligned": True}
        source_sha256 = "verified-pcd-sha256"

    item = create_proposals([Record()]).frames["registered/2"]
    assert item.image == str(depth_path)
    assert item.source_anchor_hash == Record.source_sha256


def test_create_proposals_never_uses_rgb_as_geometry_anchor(tmp_path):
    pcd_path = tmp_path / "cloud.pcd"
    pcd_path.write_text(
        "# .PCD v0.7\nVERSION .7\nFIELDS x y z\nSIZE 4 4 4\nTYPE F F F\n"
        "COUNT 1 1 1\nWIDTH 307200\nHEIGHT 1\nPOINTS 307200\nDATA ascii\n"
    )
    rgb_path = tmp_path / "rgb.jpg"
    Image.new("RGB", (1280, 960)).save(rgb_path)
    class Record:
        frame_id = "rgb/1"
        group_id = "rgb/1"
        paths = {"pcd": pcd_path, "rgb": rgb_path}
    item = create_proposals([Record()]).frames["rgb/1"]
    assert item.image == str(pcd_path)
    assert (item.width, item.height) == (640, 480)
    assert item.evidence_images == [str(rgb_path)]


def test_create_proposals_uses_organized_pcd_dimensions(tmp_path):
    pcd_path = tmp_path / "organized.pcd"
    pcd_path.write_text(
        "# .PCD v0.7\nVERSION .7\nFIELDS x y z\nSIZE 4 4 4\nTYPE F F F\n"
        "COUNT 1 1 1\nWIDTH 2\nHEIGHT 2\nPOINTS 4\nDATA ascii\n"
        "0 0 0\n1 0 0\n0 1 0\n1 1 0\n"
    )
    class Record:
        frame_id = "organized/1"
        group_id = "organized/1"
        paths = {"pcd": pcd_path}
    item = create_proposals([Record()]).frames["organized/1"]
    assert (item.width, item.height) == (2, 2)
    assert not item.dimensions_pending


@pytest.mark.parametrize(("points", "expected"), [
    (307200, (640, 480)),
    (23040, (240, 96)),
])
def test_create_proposals_maps_flat_sensor_pcd_header_without_loading_points(tmp_path, points, expected):
    pcd_path = tmp_path / "flat.pcd"
    pcd_path.write_text(
        f"# .PCD v0.7\nVERSION .7\nFIELDS x y z\nSIZE 4 4 4\nTYPE F F F\n"
        f"COUNT 1 1 1\nWIDTH {points}\nHEIGHT 1\nPOINTS {points}\nDATA ascii\n"
    )
    yaml_path = tmp_path / "intensity.yaml"
    yaml_path.write_text("not a raster image")
    class Record:
        frame_id = "flat/1"
        group_id = "flat/1"
        paths = {"pcd": pcd_path, "intensity": yaml_path}
    item = create_proposals([Record()]).frames["flat/1"]
    assert (item.width, item.height) == expected
    assert item.image == str(pcd_path)
    assert not item.dimensions_pending
