import json
from types import SimpleNamespace

from pallet.annotation import reserve_audit


def test_teacher_subset_excludes_whole_reserved_sessions(tmp_path, monkeypatch):
    protocol = tmp_path / "protocol"
    protocol.mkdir()
    (protocol / "protocol.json").write_text("{}")
    rows = [SimpleNamespace(frame_id=f"f{i}", group_id=group, domain=domain,
                            source_sha256=f"raw{i}")
            for i, (group, domain) in enumerate([
                ("date1/a", "config-a"), ("date1/a", "config-a"),
                ("date2/b", "config-a"), ("date3/c", "config-b"),
                ("date4/d", "config-b")])]
    assignments = {row.group_id: "train" for row in rows}
    labels = SimpleNamespace(frames={row.frame_id: SimpleNamespace(
        frame_id=row.frame_id, group_id=row.group_id,
        source_anchor_hash=row.source_sha256, status="pos", ignore_regions=[])
        for row in rows})
    monkeypatch.setattr(reserve_audit, "load_protocol",
                        lambda _: (rows, assignments, {}))
    monkeypatch.setattr(reserve_audit, "load_jsonl", lambda _: labels)
    monkeypatch.setattr(reserve_audit, "is_resolved", lambda frame: True)
    subset = tmp_path / "pilot.json"
    subset.write_text(json.dumps({"train": [row.frame_id for row in rows],
                                  "val": ["validation"], "test": ["test"]}))
    annotations = tmp_path / "labels.jsonl"
    annotations.write_text("labels")

    output = tmp_path / "audit"
    result = reserve_audit.reserve_audit(protocol, subset, annotations, output,
                                         per_domain=1)
    groups = json.loads((output / "audit_groups.json").read_text())
    teacher = json.loads((output / "teacher_subset.json").read_text())
    panel = json.loads((output / "audit_panel.json").read_text())
    assert result["audit_groups"] == 2
    assert len(panel["frame_ids"]) == result["audit_frames"]
    assert not {row.group_id for row in rows if row.frame_id in teacher["train"]} & set(groups)
    assert teacher["val"] == ["validation"] and teacher["test"] == ["test"]
    assert set(teacher["train"]) | set(panel["frame_ids"]) == set(
        json.loads(subset.read_text())["train"])

    held_output = tmp_path / "held_audit"
    reserve_audit.reserve_audit(protocol, subset, annotations, held_output,
                                per_domain=1, target_domain="config-b")
    held_teacher = json.loads((held_output / "teacher_subset.json").read_text())
    assert held_teacher["train"]
    assert all(row.domain != "config-b" for row in rows
               if row.frame_id in held_teacher["train"])
