"""Post-route check of complemented weights against a specialised population count."""
import argparse,json,tempfile
from hashlib import sha256
from pathlib import Path
from statistics import median
from apprendre import descriptions,learn
from neurones import build,scalar
from porter import netcheck,path_stats
HERE=Path(__file__).resolve().parent

def run(tools=None,export=None):
    original,truth,quality=learn()
    model=[(w^255,t) for w,t in original]
    expected=bytes(sum(int(scalar(x,w)>=t)<<i for i,(w,t) in enumerate(model)) for x in range(256))
    assert all(expected[x]==truth[x^255] for x in range(256))
    src,selection=descriptions(model)
    if tools:
        with tempfile.TemporaryDirectory() as tmp:
            raw=build(*tools,Path(tmp),units=('pop_unit','partition'),source=src,expected=expected,route_flags=('--router','router2'))
        if export:export.write_text(json.dumps(raw,separators=(',',':'))+'\n',encoding='utf8')
    else:raw=json.loads((HERE/'routages12.json').read_bytes())
    records={}
    for key,entry in raw.items():
        assert entry['rtl']==sha256(expected).hexdigest()
        assert netcheck(entry['mapped'],expected)==netcheck(entry['registered'],expected)
        results=[path_stats(entry['routes'][str(i)]) for i in range(1,6)]
        records[key]=dict(delays=[r['ns'] for r in results],median_ns=median(r['ns'] for r in results),cells=[r['occupied'] for r in results])
    return dict(model=model,left=selection['left'],counter_count=selection['distinct_counters'],conjugate_quality=quality['test'],routes=records)

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--rebuild',nargs=2);p.add_argument('--export',type=Path);args=p.parse_args()
    print(json.dumps(run(args.rebuild,args.export),indent=2))
