"""Fixed non-isometric weights on the HX8K and adjacent-site routing for positive gates."""
from hashlib import sha256
from itertools import combinations,product
from pathlib import Path
from random import Random
from statistics import median
import argparse,json,tempfile
from apprendre import descriptions,learn,label
from neurones import build,scalar
from porter import netcheck,path_stats
from polarites12 import plan
HERE=Path(__file__).resolve().parent

def line(parallel,median_route=False):
    layers,n=plan(parallel);ops=[];swaps=0
    for layer in layers:
        for gate in layer:
            order=list(range(n));moved=[];first=min(gate)
            ordered=sorted(gate)
            if median_route and len(gate)==3:first=ordered[1]-1
            for dest,w in enumerate(ordered,first):
                p=order.index(w)
                while p!=dest:
                    j=p+(1 if dest>p else -1)
                    moved.append((p,j));order[j],order[p]=order[p],order[j];p=j
            if median_route:assert len(moved)==max(gate)-min(gate)-len(gate)+1
            local=tuple(order.index(i) for i in gate)
            assert max(local)-min(local)+1==len(local)
            ops.extend(('swap',s) for s in moved);ops.append(('gate',local))
            ops.extend(('swap',s) for s in reversed(moved));swaps+=2*len(moved)
    for vals in product((0,1),repeat=6):
        a,b,*out=vals;w=[a,b]+[0]*(n-6)+out
        for tag,g in ops:
            if tag=='swap':i,j=g;w[i],w[j]=w[j],w[i]
            else:w[g[-1]]^=int(all(w[i] for i in g[:-1]))
        assert w==[a,b]+[0]*(n-6)+[v^(j==2*a+b) for j,v in enumerate(out)]
    return dict(width=n,local_gates=len(ops)-swaps,swaps=swaps,total=len(ops))

def run(tools=None,export=None):
    model=[(v,2) for v in (1,7,63,255)];old=learn()[0]
    def distances(m):return sorted((a^b).bit_count() for (a,_),(b,_) in combinations(m,2))
    assert distances(model)!=distances(old)
    truth=bytes(sum((scalar(x,w)>=t)<<j for j,(w,t) in enumerate(model)) for x in range(256))
    data=list(range(256));Random(9017).shuffle(data);test=data[160:]
    src,selection=descriptions(model)
    if tools:
        with tempfile.TemporaryDirectory() as path:
            raw=build(*tools,Path(path),units=('pop_unit','partition'),source=src,expected=truth,route_flags=('--router','router2'))
        if export:export.write_text(json.dumps(raw,separators=(',',':'))+'\n',encoding='utf8')
    else:raw=json.loads((HERE/'routages13.json').read_bytes())
    reports={}
    for k,r in raw.items():
        assert r['rtl']==sha256(truth).hexdigest() and netcheck(r['mapped'],truth)==netcheck(r['registered'],truth)
        vals=[path_stats(r['routes'][str(i)]) for i in range(1,6)]
        reports[k]=dict(ns=[x['ns'] for x in vals],median_ns=median(x['ns'] for x in vals),cells=[x['occupied'] for x in vals])
    return dict(weights=model,old_distances=distances(old),new_distances=distances(model),
                correct96=sum(truth[x]==1<<label(x) for x in test),reports=reports,
                line=[line(False),line(True)],median_line=[line(False,True),line(True,True)])
if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--rebuild',nargs=2);p.add_argument('--export',type=Path);a=p.parse_args()
    print(json.dumps(run(a.rebuild,a.export),indent=2))
