"""Hold out new starts after fitting a walk/jump threshold on archived paired times."""
from random import Random
from time import perf_counter_ns
from platform import python_version
from math import factorial
from pathlib import Path
import json
from sauts18 import unrank_fast,unrank,flip_length


def run():
    version=python_version()
    file='distances20-311.json' if version.startswith('3.11.') else 'distances20.json'
    train=json.loads(Path(__file__).with_name(file).read_bytes())
    def cost(cut):
        return sum(sum(r['jump'] if r['distance']>=cut else r['walk']) for r in train['rows'])
    cut=min(range(17,65),key=cost)
    r=Random(21001);period=factorial(9);starts=[]
    while len(starts)<32:
        pos=r.randrange(period)
        if pos not in train['starts'] and pos not in starts:starts.append(pos)
    rows=[]
    for gap in range(17,64):
        wrong=regret=walk_time=jump_time=best_time=0
        for i,start in enumerate(starts):
            target=(start+gap)%period
            seq=unrank_fast(9,start);expected=unrank(9,target)
            times={}
            for method in (('jump','walk') if i%2==0 else ('walk','jump')):
                tic=perf_counter_ns()
                if method=='jump':result=unrank_fast(9,target)
                else:
                    v=list(seq)
                    for t in range(start,start+gap):
                        length=flip_length(9,t%period);v[-length:]=reversed(v[-length:])
                    result=tuple(v)
                times[method]=perf_counter_ns()-tic
                assert result==expected
            best=min(times.values());loss=times['jump' if gap>=cut else 'walk']-best
            wrong+=loss>0;regret+=loss;walk_time+=times['walk'];jump_time+=times['jump'];best_time+=best
        rows.append(dict(gap=gap,errors=wrong,regret_ns=regret,walk_ns=walk_time,jump_ns=jump_time,oracle_ns=best_time))
    return dict(train_python=train['python'],test_python=version,cut=cut,starts=starts,rows=rows)


if __name__=='__main__':print(json.dumps(run(),indent=2))
