#!/usr/bin/env python3
"""Offline teaching fixture: pool compatible latency observations before p95."""
import copy
import math


def nearest_rank(values, percentile):
    if not values:
        raise ValueError("no observations")
    ordered = sorted(values)
    return ordered[math.ceil(percentile * len(ordered)) - 1]


def compatible(workers, expected):
    keys = ("metric", "unit", "window_start", "window_end", "population", "outcome", "buckets")
    for worker in workers:
        missing_metadata = [key for key in keys if key not in worker or worker[key] in (None, "")]
        if missing_metadata:
            raise ValueError("HOLD: missing required metadata: " + ", ".join(missing_metadata))
        if not isinstance(worker["buckets"], tuple) or not worker["buckets"]:
            raise ValueError("HOLD: bucket schema must be a non-empty tuple")
    names = [worker.get("name") for worker in workers]
    if len(names) != len(set(names)):
        raise ValueError("HOLD: duplicate worker ID")
    unexpected = sorted(set(names) - set(expected))
    if unexpected:
        raise ValueError("HOLD: unexpected worker(s): " + ", ".join(unexpected))
    missing = sorted(set(expected) - set(names))
    if missing:
        raise ValueError("HOLD: missing worker(s): " + ", ".join(missing) + "; absent is not zero")
    reference = tuple(workers[0][key] for key in keys)
    for worker in workers[1:]:
        if tuple(worker[key] for key in keys) != reference:
            raise ValueError("HOLD: metadata mismatch; do not pool")


def merge_cumulative(workers):
    boundaries = workers[0]["buckets"]
    for worker in workers:
        if tuple(worker["cumulative"]) != boundaries:
            raise ValueError("HOLD: bucket keys do not match declared schema")
        counts = [worker["cumulative"][boundary] for boundary in boundaries]
        if any(not isinstance(count, int) or count < 0 for count in counts):
            raise ValueError("HOLD: cumulative bucket counts must be non-negative integers")
        if counts != sorted(counts):
            raise ValueError("HOLD: worker cumulative bucket counts must not decrease")
        if counts[-1] != len(worker["raw"]):
            raise ValueError("HOLD: worker bucket total does not match completed-job count")
    merged = []
    for boundary in boundaries:
        merged.append(sum(worker["cumulative"][boundary] for worker in workers))
    if merged != sorted(merged):
        raise ValueError("cumulative bucket counts must not decrease")
    return boundaries, merged


def fixture():
    common = dict(metric="authorized_job_latency", unit="ms", window_start="2026-12-06T10:00:00Z", window_end="2026-12-06T10:10:00Z",
                  population="completed_valid_jobs", outcome="success_only",
                  buckets=(10, 20, 100, float("inf")))
    # Unequal counts: worker-a has two observations, worker-b has eight.
    return [
        dict(name="worker-a", raw=[10, 100], cumulative={10: 1, 20: 1, 100: 2, float("inf"): 2}, **common),
        dict(name="worker-b", raw=[11, 12, 13, 14, 15, 16, 17, 20], cumulative={10: 0, 20: 8, 100: 8, float("inf"): 8}, **common),
    ]


def p95_bucket_bound(boundaries, cumulative, total):
    rank = math.ceil(.95 * total)
    index = next(index for index, count in enumerate(cumulative) if count >= rank)
    lower = 0 if index == 0 else boundaries[index - 1]
    return lower, boundaries[index], rank


def self_test():
    workers = fixture()
    compatible(workers, ["worker-a", "worker-b"])
    merge_cumulative(workers)
    broken = copy.deepcopy(workers)
    broken[0]["cumulative"][20] = 0
    try:
        merge_cumulative(broken)
    except ValueError as error:
        assert "must not decrease" in str(error)
    else:
        raise AssertionError("accepted a decreasing worker cumulative sequence")
    wrong_keys = copy.deepcopy(workers)
    wrong_keys[0]["cumulative"].pop(20)
    try:
        merge_cumulative(wrong_keys)
    except ValueError as error:
        assert "bucket keys" in str(error)
    else:
        raise AssertionError("accepted incomplete bucket keys")
    missing_metadata = copy.deepcopy(workers)
    missing_metadata[1].pop("population")
    try:
        compatible(missing_metadata, ["worker-a", "worker-b"])
    except ValueError as error:
        assert "missing required metadata" in str(error)
    else:
        raise AssertionError("accepted missing population metadata")


def main():
    workers = fixture()
    compatible(workers, ["worker-a", "worker-b"])
    per_worker = [nearest_rank(worker["raw"], .95) for worker in workers]
    counts = [len(worker["raw"]) for worker in workers]
    pooled = [value for worker in workers for value in worker["raw"]]
    naive = sum(per_worker) / len(per_worker)
    weighted = sum(p * n for p, n in zip(per_worker, counts)) / sum(counts)
    boundaries, merged = merge_cumulative(workers)
    lower, upper, rank = p95_bucket_bound(boundaries, merged, len(pooled))
    assert per_worker == [100, 20]
    assert (naive, weighted, nearest_rank(pooled, .95), merged, (lower, upper, rank)) == (60.0, 36.0, 100, [1, 9, 10, 10], (20, 100, 10))
    self_test()
    print("offline synthetic fixture; network_requests=0")
    print("metadata=metric:authorized_job_latency unit:ms window:2026-12-06T10:00:00Z/2026-12-06T10:10:00Z population:completed_valid_jobs outcome:success_only")
    for worker, p95 in zip(workers, per_worker):
        print(f"{worker['name']} n={len(worker['raw'])} raw={worker['raw']} p95_nearest_rank={p95}ms")
    print(f"naive_mean_of_worker_p95s={naive:.1f}ms (not fleet p95)")
    print(f"traffic_weighted_mean_of_worker_p95s={weighted:.1f}ms (still not fleet p95)")
    print(f"pooled_n={len(pooled)} sorted={sorted(pooled)}")
    print(f"pooled_p95_nearest_rank={nearest_rank(pooled, .95)}ms (rank=ceil(0.95*{len(pooled)})={rank})")
    print("cumulative_buckets_per_worker: " + "; ".join(
        (f"<={boundary}ms" if math.isfinite(boundary) else "<=+Inf") + " [" + ",".join(str(worker["cumulative"][boundary]) for worker in workers) + "]"
        for boundary in boundaries
    ))
    print("merged_cumulative_buckets: " + "; ".join((f"<={boundary}ms" if math.isfinite(boundary) else "<=+Inf") + f" {count}" for boundary, count in zip(boundaries, merged)))
    print(f"histogram_p95_bound=({lower},{upper}]ms; bucket quantile is an estimate, not an exact {upper}ms observation")
    try:
        compatible(workers, ["worker-a", "worker-b", "worker-c"])
    except ValueError as error:
        print(str(error))
    mismatch = [dict(worker) for worker in workers]
    mismatch[1]["window_end"] = "2026-12-06T10:05:00Z"
    try:
        compatible(mismatch, ["worker-a", "worker-b"])
    except ValueError as error:
        print(str(error))
    print("PASS: merge raw observations or compatible bucket counts first; record failures/timeouts in a separate denominator")


if __name__ == "__main__":
    main()
