"""Recompute deadline-qualified live + completed background searches from the measured A10 clocks."""
import argparse
from bisect import bisect_right
import csv
from hashlib import sha256
import json
from pathlib import Path
from zipfile import ZipFile

SOURCE_SHA = '26fa6e7aeed7624c91db0b24bd0cc63a4c7bd9e1db46acbf3a1f919ba12a5ce1'
CANDIDATE = 'layer-group-b32'
ARMS = ('foreground-only','shared-priority-b32','ordinary-resident-mps-b32','ordinary-opportunistic-query',CANDIDATE)
SCHEDULES = ('smooth','burst')
WINDOW_END_NS = 300_000_000_000
DEADLINE_LIMIT_NS = 5_000_000_000


def read_clock_archive(source):
    if source.stat().st_size != 496568 or sha256(source.read_bytes()).hexdigest() != SOURCE_SHA:
        raise ValueError('expected the original ten-condition A10 clock export')
    with ZipFile(source) as archive:
        clocks = json.loads(archive.read('clocks.json'))
        original = json.loads(archive.read('containment.json'))
    if clocks['run'] != 44480508310 or original['run'] != clocks['run']:
        raise ValueError('different physical run')
    cells = {}
    for cell in clocks['cells']:
        key=(cell['schedule'], cell['arm'])
        if key in cells or cell['window_end_ns'] != WINDOW_END_NS or len(cell['foreground']) != 600:
            raise ValueError('duplicate, short or incomplete condition')
        times = sorted(end-start for start,end in cell['foreground'])
        if not 0 < times[0] <= times[-1] <= DEADLINE_LIMIT_NS:
            raise ValueError('original scored foreground return outside protocol')
        credited = {job for job,_,end in cell['completed_background'] if end <= WINDOW_END_NS}
        ref, = [r for r in original['cells'] if (r['schedule'],r['arm'])==key]
        if len(credited) != ref['correct_background_searches']:
            raise ValueError('different original correct background census')
        cells[key] = (times,len(credited))
    if set(cells) != {(schedule,arm) for schedule in SCHEDULES for arm in ARMS}:
        raise ValueError('missing condition')
    return cells


def score(cells,schedule,threshold):
    totals = {}
    on_time = {}
    for arm in ARMS:
        times, bg = cells[schedule,arm]
        on_time[arm] = bisect_right(times,threshold)
        totals[arm] = bg + on_time[arm]
    strongest = max(totals[arm] for arm in ARMS if arm != CANDIDATE)
    best = [arm for arm in ARMS if arm != CANDIDATE and totals[arm]==strongest]
    return on_time,totals,best,totals[CANDIDATE]-strongest


def evaluate(cells,schedule,out):
    changes = {0}
    for arm in ARMS:
        changes.update(cells[schedule,arm][0])
    changes = sorted(changes)
    segments = []
    peak = None
    with (out/f'{schedule}-all-deadlines.csv').open('x',newline='') as handle:
        writer=csv.writer(handle)
        writer.writerow(['deadline_from_ns_inclusive','deadline_to_ns_exclusive',*ARMS,'strongest_comparator','candidate_minus_strongest'])
        for start,end in zip(changes,changes[1:]+[DEADLINE_LIMIT_NS+1]):
            _,totals,best,margin=score(cells,schedule,start)
            writer.writerow([start,end,*[totals[a] for a in ARMS],'+'.join(best),margin])
            if peak is None or margin>peak['extra_outputs']:
                peak=dict(extra_outputs=margin,deadline_ns=start,counts=totals,comparator=best,
                          descriptive_best_over_observed_deadlines=True)
            if margin>0:
                if segments and segments[-1][1]==start:
                    segments[-1][1]=end
                else:
                    segments.append([start,end])
    examples = []
    for ms in (250,300,500,750,1000,1250,1500,2000,5000):
        fg,totals,best,margin=score(cells,schedule,ms*1_000_000)
        examples.append(dict(deadline_ms=ms,live_on_time=fg,total_correct_on_time_or_background=totals,
                             strongest_comparator=best,extra_vs_strongest=margin))
    return dict(background_credited_5min={a:cells[schedule,a][1] for a in ARMS},
                full_curve_rows=len(changes),strict_win_intervals_ns_half_open=segments,
                maximum_observed_advantage=peak,previously_reported_deadlines=examples)


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('clock_archive',type=Path)
    parser.add_argument('output_dir',type=Path)
    args=parser.parse_args()
    cells=read_clock_archive(args.clock_archive)
    args.output_dir.mkdir(exist_ok=True)
    report=dict(gpu_run=44480508310,clock_sha256=SOURCE_SHA,research_outcome=True,live_query_limit_ns=DEADLINE_LIMIT_NS,
        metric='One credited output is one correctly completed 32-document rerank: a foreground query returned within the chosen deadline, or a background query returned within its original 300-second window. Both count once.',
        scope='Post-hoc equal-value scenario. All integer-nanosecond foreground deadlines from zero through the original five seconds are shown. Strongest comparator is the best observed count among four complete comparison conditions at each deadline. One five-minute condition per mode and schedule on one A10; no replicated uncertainty or prediction of cloud-provider performance. The original relative p95 gate is separate and failed on both schedules.',
        schedules={s:evaluate(cells,s,args.output_dir) for s in SCHEDULES})
    with (args.output_dir/'useful-outputs.json').open('x') as handle:
        json.dump(report,handle,indent=2,allow_nan=False)
        handle.write('\n')
