"""Measure which synthetic evaluation cases a pinned DataLoader emits.

Run with Python 3.13.17 and CPU PyTorch 2.9.1+cpu on Windows:
    python -I -B replay.py
Compare the JSON stdout with observations.json.
"""

import hashlib
import json
import multiprocessing
import platform
from collections import Counter
from pathlib import Path

import torch
from torch.utils.data import DataLoader, IterableDataset, get_worker_info


CASE_IDS = tuple(f"case-{index:02d}" for index in range(10))
BATCH_SIZE = 3
TORCH_VERSION = "2.9.1+cpu"
TORCH_REVISION = "5811a8d7da873dd699ff6687092c225caffcf1bb"


class EvaluationCases(IterableDataset):
    def __iter__(self):
        worker = get_worker_info()
        if worker is None:
            yield from (("main", case_id) for case_id in CASE_IDS)
            return

        label = f"worker-{worker.id}"
        for case_id in CASE_IDS[worker.id :: worker.num_workers]:
            yield label, case_id


def replay(worker_count, drop_last):
    loader = DataLoader(
        EvaluationCases(),
        batch_size=BATCH_SIZE,
        num_workers=worker_count,
        drop_last=drop_last,
        multiprocessing_context="spawn" if worker_count else None,
        in_order=True,
    )
    batches = []
    observed_by_worker = (
        {"worker-0": [], "worker-1": []} if worker_count else {"main": []}
    )
    for worker_labels, case_ids in loader:
        labels = set(worker_labels)
        if len(labels) != 1:
            raise RuntimeError(f"Batch has mixed worker labels: {worker_labels}")
        worker_label = next(iter(labels))
        batches.append({"worker": worker_label, "case_ids": list(case_ids)})
        observed_by_worker[worker_label].extend(case_ids)

    ordered_ids = [case_id for batch in batches for case_id in batch["case_ids"]]
    counts = Counter(ordered_ids)
    return {
        "num_workers": worker_count,
        "drop_last": drop_last,
        "batches": batches,
        "ordered_ids": ordered_ids,
        "missing_ids": [case_id for case_id in CASE_IDS if not counts[case_id]],
        "duplicate_ids": {
            case_id: count for case_id, count in counts.items() if count > 1
        },
        "observed_ids_by_worker": observed_by_worker,
        "scored_denominator": len(ordered_ids),
    }


def source_pins():
    torch_root = Path(torch.__file__).resolve().parent
    paths = (
        "utils/data/dataloader.py",
        "utils/data/_utils/fetch.py",
        "utils/data/_utils/worker.py",
    )
    return [
        {
            "source_url": (
                f"https://github.com/pytorch/pytorch/blob/{TORCH_REVISION}/torch/{path}"
            ),
            "installed_sha256": hashlib.sha256(
                (torch_root / path).read_bytes()
            ).hexdigest(),
        }
        for path in paths
    ]


def main():
    if platform.system() != "Windows":
        raise RuntimeError("This pilot requires the Windows runtime.")
    if (
        torch.__version__ != TORCH_VERSION
        or torch.version.git_version != TORCH_REVISION
        or torch.version.cuda is not None
    ):
        raise RuntimeError(f"Unexpected PyTorch build: {torch.__version__}")

    results = {
        "runtime": {
            "os": platform.system(),
            "python": platform.python_version(),
            "torch": torch.__version__,
            "torch_git_revision": torch.version.git_version,
            "torch_cuda": torch.version.cuda,
        },
        "source_pins": source_pins(),
        "documentation_url": (
            "https://docs.pytorch.org/docs/2.9/data.html#multi-process-data-loading"
        ),
        "fixed_case_ids": CASE_IDS,
        "batch_size": BATCH_SIZE,
        "worker_context": "spawn",
        "in_order": True,
        "shard_rule": "worker i receives the input positions i, i+num_workers, ...",
        "denominator_rule": "Count each emitted case once as a scored occurrence.",
        "runs": [
            replay(worker_count, drop_last)
            for worker_count in (0, 2)
            for drop_last in (False, True)
        ],
    }
    print(json.dumps(results, indent=2))


if __name__ == "__main__":
    multiprocessing.freeze_support()
    main()
