"""Reproduce preference ranges for seven measured uses of one A10.

Usage: python3 warm-policy-preferences.py warm-policy-seeds.csv > preferences.csv
Eight-policy control: append --with-bare-serving warm-bare-serving.csv
Input: https://benchmarks.nodus-compute.ai/benchmarks/downloads/warm-policy-seeds.csv
Originals: https://benchmarks.nodus-compute.ai/benchmarks/downloads/warm-governor-originals.json

Utility is timely responses + w * matched training updates. The nonnegative
weight w is an illustrative preference in responses per update, not a price.
Each reported interval wins or ties every included policy on every seed under
both published latency calibrations. Empty intervals remain visible. The two
calibrations reuse the same physical traces, not independent replications.
This is retrospective fixed-policy arithmetic, not a measured adaptive policy.
The input counts were reconstructed from public original request/training clocks
with warm-policy-outcomes.py --by-seed; this reader does not rerun a GPU.
"""
from collections import defaultdict
from fractions import Fraction
from pathlib import Path
import csv
import hashlib
import io
import sys

if sys.flags.optimize:
    raise RuntimeError('Normal Python required to preserve fixed-input checks')
if len(sys.argv) not in (2,4) or (len(sys.argv)==4 and sys.argv[2]!='--with-bare-serving'):
    raise SystemExit('Usage: warm-policy-preferences.py warm-policy-seeds.csv [--with-bare-serving warm-bare-serving.csv]')
raw = Path(sys.argv[1]).read_bytes()
if hashlib.sha256(raw).hexdigest() != '55a805bbdb28e71071c4853bef79de80ddf1c1abb45488aba941829dfb514ec8':
    raise ValueError('Unexpected public seed table')
policies = {'SM', 'GOV', 'GOV40', 'M100P', 'M25', 'M50', 'SHPL'}
sources = [raw]
if len(sys.argv)==4:
    bare = Path(sys.argv[3]).read_bytes()
    if hashlib.sha256(bare).hexdigest() != '70fb8c7d52b63d144b21cf2994388aaa26f207ca579c7b599448f7ea06695228':
        raise ValueError('Unexpected public bare-serving table')
    sources.append(bare)
    policies.add('S')
cells = defaultdict(dict)
for data in sources:
    for row in csv.DictReader(io.StringIO(data.decode())):
        key = int(row['load']), int(row['seed']), row['calibration']
        if row['policy'] in cells[key]:
            raise ValueError('Duplicate policy observation')
        cells[key][row['policy']] = (int(row['timely_both']), int(row['matched_training_updates']), int(row['offered']))
if len(cells) != 18 or any(set(cell) != policies for cell in cells.values()):
    raise ValueError('Incomplete policy census')
if any(len({offered for _, _, offered in cell.values()}) != 1 for cell in cells.values()):
    raise ValueError('Unmatched offer denominator')
output = io.StringIO(newline='')
writer = csv.writer(output)
writer.writerow(['offered_load_pct', 'policy', 'shared_interval', 'min_responses_per_update', 'max_responses_per_update'])
for load in (10, 30, 60):
    for policy in sorted(policies):
        low, high, possible = Fraction(0), None, True
        for (observed_load, seed, calibration), cell in cells.items():
            if observed_load != load:
                continue
            responses, updates, _ = cell[policy]
            for other_responses, other_updates, _ in cell.values():
                gain = updates - other_updates
                deficit = other_responses - responses
                if gain > 0:
                    low = max(low, Fraction(deficit, gain))
                elif gain < 0:
                    bound = Fraction(deficit, gain)
                    high = bound if high is None else min(high, bound)
                elif deficit > 0:
                    possible = False
        possible = possible and (high is None or low <= high)
        writer.writerow([load, policy, possible, low if possible else '',
                         ('unbounded' if high is None else high) if possible else ''])
sys.stdout.buffer.write(output.getvalue().encode())
