import pytest

from pallet.annotation import (AnnotationSet, Box, FrameAnnotation, Provenance, Review,
                               is_resolved, record_review, reference_eligible, seal_splits)
from pallet.cli import _check_source_provenance, _partition, _record_run_config
from pallet.data import FrameRecord


def test_heldout_domain_excludes_cross_domain_duplicate_group():
    class DomainRecord(FrameRecord):
        @property
        def domain(self):
            return "held" if self.frame_id.startswith("target") else "source"

    records = [
        DomainRecord("target/a", "duplicate", "v", {}),
        DomainRecord("source/a", "duplicate", "v", {}),
        DomainRecord("source/b", "g2", "v", {}),
        DomainRecord("source/c", "g3", "v", {}),
    ]
    labels = AnnotationSet(FrameAnnotation(row.frame_id, row.group_id, "dummy.png", 32, 32,
                                           source_anchor_hash="synthetic-anchor")
                           for row in records)
    seal_splits(labels, {"duplicate": "test", "g2": "train", "g3": "val"})
    source = _partition(records, labels, "train", holdout_domain="held")
    source += _partition(records, labels, "val", holdout_domain="held")
    assert {row.group_id for row in source} == {"g2", "g3"}
    assert {row.frame_id for row in _partition(records, labels, "test", holdout_domain="held")} == {"target/a"}
    for seed in (42, 123, 999):
        assert {row.frame_id for row in _partition(records, labels, "train", seed=seed)} == {"source/b"}
        assert {row.frame_id for row in _partition(records, labels, "val", seed=seed)} == {"source/c"}
        assert {row.frame_id for row in _partition(records, labels, "test", seed=seed)} == {"target/a", "source/a"}


def test_assisted_train_review_cannot_become_blind_test_reference():
    frame = FrameAnnotation("f", "g", "sensor.png", 32, 32,
                            source_anchor_hash="synthetic-anchor", split="train")
    box = Box(2, 2, 10, 10)
    record_review(frame, Review("a", "approve", blind=False), status="pos", boxes=[box])
    record_review(frame, Review("b", "approve", blind=False))
    assert is_resolved(frame)
    frame.split = "test"
    assert not reference_eligible(frame)
    assert not is_resolved(frame, require_blind=True)


def test_heldout_teacher_provenance_is_rejected():
    class DomainRecord(FrameRecord):
        @property
        def domain(self):
            return "held" if self.frame_id == "target" else "source"

    records = [DomainRecord("target", "test-group", "v", {}),
               DomainRecord("source", "train-group", "v", {})]
    source = FrameAnnotation("source", "train-group", "dummy.png", 32, 32,
                             provenance=[Provenance("detector", trained_group_ids=("test-group",))])
    target = FrameAnnotation("target", "test-group", "dummy.png", 32, 32)
    labels = AnnotationSet([source, target])
    with pytest.raises(ValueError, match="target-trained"):
        _check_source_provenance(records, labels, "held")


def test_resume_requires_same_label_and_experiment_identity(tmp_path):
    path = tmp_path / "run.json"
    _record_run_config(path, {"annotation_sha256": "a", "seed": 42})
    _record_run_config(path, {"annotation_sha256": "a", "seed": 42})
    with pytest.raises(ValueError, match="different label snapshot"):
        _record_run_config(path, {"annotation_sha256": "b", "seed": 42})
