"""Offline replica-validation example for a finite model sweep. Run with Python 3.10+.

Anderson (2020), BOINC: A Platform for Volunteer Computing,
https://doi.org/10.1007/s10723-019-09497-9. This is an independent teaching example.

Run the first two commands on separate machines, then collect both output files:
    python replica_validation.py --worker A > a.json
    python replica_validation.py --worker B > b.json
    python replica_validation.py --verify a.json b.json
The caller assigns worker IDs and transfers the files. With no arguments the
example simulates a conflicting report and a duplicate locally.
"""
import argparse
import json
from collections import Counter, defaultdict
from dataclasses import asdict, dataclass
from itertools import combinations, product
from math import comb
from pathlib import Path

GRID = range(-2, 3)
BINS = tuple(range(-4, 5))
VERSION = "sum-at-one-v1"


@dataclass(frozen=True)
class Report:
    version: str
    shard: int
    worker: str
    counts: tuple[int, ...]


def compute(shard):
    """Histogram of y(1) = a + b for fixed a and five choices of b."""
    counts = Counter(shard + b for b in GRID)
    return tuple(counts[output] for output in BINS)


def agreed_counts(shard, reports):
    """Accept one exact histogram supported by at least two distinct worker IDs."""
    by_worker = defaultdict(set)
    for report in reports:
        if (report.version != VERSION or report.shard != shard or not report.worker
                or len(report.counts) != len(BINS)
                or any(type(n) is not int or n < 0 for n in report.counts)
                or sum(report.counts) != len(GRID)):
            continue
        by_worker[report.worker].add(report.counts)
    votes = Counter(next(iter(values)) for values in by_worker.values() if len(values) == 1)
    winners = [result for result, count in votes.items() if count >= 2]
    return winners[0] if len(winners) == 1 else None


def simulated_reports():
    reports = []
    for shard in GRID:
        correct = compute(shard)
        # Host IDs and submissions are simulated locally.
        first = Report(VERSION, shard, "A", correct)
        wrong = correct[-1:] + correct[:-1]
        conflict = Report(VERSION, shard, "B", wrong)
        assert agreed_counts(shard, [first, first, conflict]) is None
        reports.extend([first, first, conflict, Report(VERSION, shard, "C", correct)])
    return reports


def read_reports(files):
    reports = []
    for filename in files:
        # Windows PowerShell may write a UTF-8 byte order mark.
        rows = json.loads(filename.read_text(encoding="utf-8-sig"))
        for row in rows:
            if not isinstance(row["worker"], str) or type(row["shard"]) is not int:
                raise ValueError(f"Invalid worker or shard in {filename}")
            reports.append(Report(row["version"], row["shard"], row["worker"], tuple(row["counts"])))
    return reports


def check(reports):
    total = [0] * len(BINS)
    for shard in GRID:
        agreed = agreed_counts(shard, reports)
        if agreed is None:
            raise ValueError(f"No agreement for shard {shard}")
        total = [x + y for x, y in zip(total, agreed)]
    collisions = sum(comb(n, 2) for n in total)
    # Compare against a different algorithm that enumerates pairs directly.
    direct = sum(a + b == c + d for (a, b), (c, d) in combinations(product(GRID, repeat=2), 2))
    if collisions != direct:
        raise ValueError("Independent calculation disagrees")
    print(f"{len(GRID)} accepted shards, {sum(total)} models, {collisions} indistinguishable pairs")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument("--worker", metavar="ID", help="write this worker's five results as JSON")
    mode.add_argument("--verify", nargs="+", type=Path, help="compare JSON reports from independent workers")
    args = parser.parse_args()
    if args.worker:
        print(json.dumps([asdict(Report(VERSION, shard, args.worker, compute(shard))) for shard in GRID]))
    else:
        check(read_reports(args.verify) if args.verify else simulated_reports())
