import hashlib
import json
from types import SimpleNamespace

from pallet import progress_v5


def _write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value))


def test_completed_round_progress_uses_frozen_labels(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    round_dir = tmp_path / "outputs/rounds_v5/round_003"
    frozen = tmp_path / "frozen.jsonl"
    frozen.write_text("frozen snapshot\n")
    _write_json(round_dir / "round.json", {
        "state": "complete", "frame_ids": ["a", "b"],
        "reviewed_labels": str(frozen),
        "reviewed_labels_sha256": hashlib.sha256(frozen.read_bytes()).hexdigest(),
    })
    latest_labels = tmp_path / "stale.jsonl"
    latest_labels.write_text("stale snapshot\n")
    _write_json(tmp_path / "outputs/review_round_003_small/latest.json", {
        "annotation_path": str(latest_labels), "paired_batches": 1,
        "pending_adjudication": 0, "errors": [],
    })

    monkeypatch.setattr(progress_v5, "load_jsonl", lambda _: SimpleNamespace(frames={
        "a": SimpleNamespace(status="pos"), "b": SimpleNamespace(status="negative")
    }))
    monkeypatch.setattr(progress_v5, "is_resolved", lambda frame: True)

    result = progress_v5._candidate_round(3)
    assert result["status"] == {"pos": 1, "negative": 1}
    assert result["resolved"] == 2
    assert result["label_snapshot"] == str(frozen)
    assert result["label_sha256"] == result["frozen_round_labels_sha256"]


def test_candidate_review_progress_counts_normalized_reviews_before_ingest(tmp_path):
    root = tmp_path / "round006"
    _write_json(root / "tasks/train_000.json", {
        "frames": [{"index": index} for index in range(5)]
    })
    _write_json(root / "tasks/train_001.json", {
        "frames": [{"index": index} for index in range(5)]
    })
    a_review = root / "reviews/a_train_000.json"
    _write_json(a_review, {
        "frames": [{"index": index} for index in range(5)]
    })
    b_review = root / "reviews/b_train_000.json"
    _write_json(b_review, {
        "frames": [{"index": index} for index in range(4)]
    })
    _write_json(root / "reviews/a_train_000.manifest.json", {
        "task_sha256": progress_v5.file_digest(root / "tasks/train_000.json"),
        "normalized_review_sha256": progress_v5.file_digest(a_review),
    })
    _write_json(root / "reviews/b_train_000_manifest.json", {
        "task_sha256": progress_v5.file_digest(root / "tasks/train_000.json"),
        "review_file": b_review.name,
        "review_sha256": progress_v5.file_digest(b_review),
    })
    _write_json(root / "reviews/b_train_001.json", {
        "frames": [{"index": index} for index in range(5)]
    })
    adjudication_task = root / "adjudication_tasks/train_000.json"
    _write_json(adjudication_task, {"task_id": "train_000", "frames": []})
    c_review = root / "reviews/c_train_000.json"
    _write_json(c_review, {"frames": [{"index": index} for index in range(5)]})
    _write_json(root / "reviews/c_train_000_manifest.json", {
        "task_id": "train_000",
        "task_sha256": progress_v5.file_digest(adjudication_task),
        "review_path": "reviews/c_train_000.json",
        "review_sha256": progress_v5.file_digest(c_review),
    })
    _write_json(root / "reviews/raw_a_train_001.json", {
        "frames": [{"index": index} for index in range(5)]
    })

    result = progress_v5._candidate_review_progress(6, root)

    assert result["tasks"] == 2
    assert result["frames_expected"] == 10
    assert result["reviewers"]["a"] == {
        "tasks_submitted": 1, "frames_reviewed": 5, "frames_expected": 10,
        "pending_frames": 5, "invalid_entries": 0, "unverified_files": 0,
    }
    assert result["reviewers"]["b"]["frames_reviewed"] == 4
    assert result["reviewers"]["b"]["pending_frames"] == 6
    assert result["reviewers"]["b"]["unverified_files"] == 1
    assert result["reviewers"]["c"]["frames_reviewed"] == 5
    assert result["reviewers"]["c"]["pending_frames"] == 5


def test_round_discovery_includes_new_rounds(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    for index in (1, 3, 4):
        _write_json(tmp_path / f"outputs/rounds_v5/round_{index:03d}/round.json", {
            "state": "running", "frame_ids": []
        })

    rounds = progress_v5._discover_rounds()

    assert list(rounds) == ["001", "003", "004"]


def test_round_discovery_includes_preselected_round(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    _write_json(tmp_path/"outputs/rounds_v5/round_004/preselection.json",
                {"train":["one","two"]})
    rounds=progress_v5._discover_rounds()
    assert rounds["004"]["round_state"]=="preselected"
    assert rounds["004"]["planned"]==2


def test_progress_uses_latest_review_queue_manifest(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    old = tmp_path / "outputs/stages/full_review_queue_v5d"
    new = tmp_path / "outputs/stages/full_review_queue_v5e"
    _write_json(old / "manifest.json", {"waiting": {"train": 1}, "conflicts": []})
    _write_json(new / "manifest.json", {
        "protocol_sha256": "protocol", "primary_labels_sha256": "labels",
        "batch_limit": 1024, "resolved": {"train": 20},
        "inflight": {"train": 0}, "waiting": {"train": 80},
        "conflicts": [], "reference_rule": "blind references only",
    })

    result = progress_v5._latest_full_review_queue()

    assert result["name"] == "full_review_queue_v5e"
    assert result["waiting"] == {"train": 80}
    assert result["conflicts"] == 0
    assert len(result["manifest_sha256"]) == 64


def test_preselected_round_parent_snapshot_is_found_by_panel_hash(tmp_path):
    labels = tmp_path / "round5.jsonl"
    labels.write_text("parent labels\n")
    digest = hashlib.sha256(labels.read_bytes()).hexdigest()
    _write_json(tmp_path / "rounds/round_005/round.json", {
        "state": "complete", "reviewed_labels": str(labels),
        "reviewed_labels_sha256": digest,
    })
    panel = tmp_path / "stages/round_006/audit_panel.json"
    _write_json(panel, {"input_labels_sha256": digest})

    result = progress_v5._labels_snapshot_for_sha(
        json.loads(panel.read_text())["input_labels_sha256"],
        rounds_root=tmp_path / "rounds",
    )

    assert result == str(labels)


def test_teacher_progress_reports_compact_metrics_and_completion(tmp_path):
    run_dir = tmp_path / "teacher_006"
    _write_json(run_dir / "run.json", {
        "recipe": "official_research_constrained", "family": "yolo26",
        "seed": 42, "size": 640, "batch_size": 16, "effective_batch": 16,
        "epochs": 300, "device_uuid": "GPU-test", "code_sha256": "code",
        "source_snapshot_id": "snapshot", "git_commit": "commit", "git_dirty": False,
    })
    metrics = run_dir / "metrics.jsonl"
    metrics.parent.mkdir(parents=True, exist_ok=True)
    metrics.write_text(json.dumps({"epoch": 4, "validation": {
        "AP50": .8, "AP75": .4, "AP50_95": .3, "precision": .7,
        "recall_at_threshold_iou_0.5": .6, "per_frame": ["large detail"],
    }}) + "\n{")

    running = progress_v5._teacher_progress(tmp_path)["teacher_006"]
    assert running["state"] == "incomplete"
    assert running["logged_epochs"] == 5
    assert running["best_AP50_95"] == .3
    assert "per_frame" not in running["latest_validation"]

    _write_json(run_dir / "completed.json", {
        "target_epochs": 300, "stopped_reason": "patience",
    })
    completed = progress_v5._teacher_progress(tmp_path)["teacher_006"]
    assert completed["state"] == "complete"
    assert completed["stopped_reason"] == "patience"
    assert len(completed["completion_manifest_sha256"]) == 64


def test_full_review_batch_progress_separates_reviews_from_adjudication(tmp_path):
    directory = tmp_path / "full_review_train_005_v5"
    _write_json(directory / "train_index.json", ["f1", "f2", "f3", "f4", "f5"])
    _write_json(directory / "tasks/train_000.json", {"frames": [1, 2, 3, 4, 5]})
    _write_json(directory / "reviews/a_train_000.json", {
        "frames": [{"index": index} for index in range(5)]
    })
    _write_json(directory / "reviews/b_train_000.json", {
        "frames": [{"index": index} for index in range(5)]
    })
    _write_json(directory / "latest.json", {
        "consensus_frames": 2, "adjudicated_frames": 1,
        "pending_adjudication": 2,
    })
    _write_json(directory / "errors.json", [])

    result = progress_v5._full_review_batch_progress(tmp_path)
    assert list(result["full_review_train_005_v5"]) == ["train"]
    batch = result["full_review_train_005_v5"]["train"]

    assert batch["selected_frames"] == 5
    assert batch["tasks"] == 1
    assert batch["reviewer_frames"] == {"a": 5, "b": 5, "c": 0}
    assert batch["consensus_frames"] == 2
    assert batch["adjudicated_frames"] == 1
    assert batch["pending_adjudication"] == 2
    assert batch["read_errors"] == 0
