"""Offline timing arithmetic on a frozen schedule; no model or load test."""
from collections import Counter
import json
import math
from pathlib import Path
import sys

STATES = ("completed", "timeout", "rejected", "not_dispatched", "in_flight")
SCHEDULE_FIELDS = {"request_id", "scheduled_ms"}
OBSERVATION_FIELDS = {"request_id", "status", "dispatch_ms", "first_output_ms", "end_ms"}
METRICS = ("client_ttft_ms", "scheduled_ttft_ms", "client_e2e_ms", "scheduled_e2e_ms")


def _ms(value):
    if type(value) not in (int, float):
        raise ValueError("Offsets must be non-negative finite numbers, not booleans")
    try:
        valid = math.isfinite(value) and value >= 0
    except OverflowError:
        valid = False
    if not valid:
        raise ValueError("Offsets must be non-negative finite numbers")
    return value


def _index(records, fields):
    if not isinstance(records, list):
        raise ValueError("Schedule and observations must be lists")
    result = {}
    for record in records:
        if not isinstance(record, dict) or set(record) != fields:
            raise ValueError("Unexpected or missing record fields")
        key = record["request_id"]
        if not isinstance(key, str) or not key.strip():
            raise ValueError("Request IDs must be non-empty strings")
        if key in result:
            raise ValueError("Duplicate request ID")
        result[key] = record
    return result


def _stats(values):
    """Nearest-rank p50/p95, explicitly conditional on supplied samples."""
    values = sorted(values)
    n = len(values)
    if not n:
        return {"n": 0, "mean": None, "p50": None, "p95": None}
    try:
        mean = math.fsum(value / n for value in values)
    except OverflowError as exc:
        raise ValueError("Statistics exceed supported numeric range") from exc
    return {"n": n, "mean": round(mean, 6), "p50": values[math.ceil(0.50 * n) - 1], "p95": values[math.ceil(0.95 * n) - 1]}


def summarize_latency(schedule, observations, cutoff_ms):
    """Require one observation for every planned arrival, without mutating input.

    All offsets must come from the same monotonic clock. For a non-completed
    request, end_ms is an observation event, never an inferred completion.
    A timeout is a client event and does not establish that server work stopped.
    """
    cutoff_ms = _ms(cutoff_ms)
    plan = _index(schedule, SCHEDULE_FIELDS)
    observed = _index(observations, OBSERVATION_FIELDS)
    if plan.keys() != observed.keys():
        raise ValueError("Schedule and observation IDs must match exactly")
    counts = Counter({state: 0 for state in STATES})
    per_request = []
    for key in sorted(plan):
        arrival = _ms(plan[key]["scheduled_ms"])
        record = observed[key]
        state = record["status"]
        if state not in STATES:
            raise ValueError("Unsupported observation state")
        end = _ms(record["end_ms"])
        if not arrival <= end <= cutoff_ms:
            raise ValueError("Observation end must lie between arrival and cutoff")
        dispatch, first = record["dispatch_ms"], record["first_output_ms"]
        if state == "not_dispatched":
            if dispatch is not None or first is not None:
                raise ValueError("Non-dispatched work cannot have dispatch or output")
        else:
            dispatch = _ms(dispatch)
            if not arrival <= dispatch <= end:
                raise ValueError("Dispatch must lie between arrival and observation end")
            if first is not None:
                first = _ms(first)
                if not dispatch <= first <= end:
                    raise ValueError("First output must lie between dispatch and end")
            if state == "completed" and first is None:
                raise ValueError("A completed streamed response requires first output")
            if state == "rejected" and first is not None:
                raise ValueError("This contract rejects output on a rejected request")
            if state == "in_flight" and end != cutoff_ms:
                raise ValueError("In-flight observation must end at the cutoff")
        counts[state] += 1
        per_request.append({
            "request_id": key,
            "status": state,
            "generator_wait_ms": None if dispatch is None else dispatch - arrival,
            "client_observed_duration_ms": None if dispatch is None else end - dispatch,
            "client_ttft_ms": None if first is None else first - dispatch,
            "scheduled_ttft_ms": None if first is None else first - arrival,
            "client_e2e_ms": end - dispatch if state == "completed" else None,
            "scheduled_e2e_ms": end - arrival if state == "completed" else None,
        })
    completed = [row for row in per_request if row["status"] == "completed"]
    return {
        "counts": {"scheduled": len(plan), **counts},
        "latency_population": "completed_requests_only",
        "percentile_method": "nearest_rank_ceil_p_times_n_no_interpolation",
        "units": "milliseconds",
        "completed_latency": {metric: _stats([row[metric] for row in completed]) for metric in METRICS},
        "per_request": per_request,
    }


def main():
    if len(sys.argv) > 2:
        raise SystemExit("Usage: python3 latency_boundaries.py [synthetic-fixture.json]")
    path = Path(sys.argv[1]) if len(sys.argv) == 2 else Path(__file__).with_name("synthetic-latency-boundaries.json")
    fixture = json.loads(path.read_text(encoding="utf-8"))
    if fixture.get("synthetic") is not True or fixture.get("status") != "synthetic_arithmetic_fixture_not_a_run":
        raise ValueError("This demonstration CLI accepts labelled synthetic fixtures only")
    report = summarize_latency(fixture["schedule"], fixture["observations"], fixture["observation_cutoff_ms"])
    print(json.dumps({"status": "synthetic_timing_arithmetic_only", "report": report}, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
