"""Exact truth table and routed cost of a fixed four-neuron binary layer."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import shutil
from statistics import median
import tempfile

from chiffres import read_cells
from porter import netcheck, path_stats
from routage import registered_core, run_command, SEEDS

HERE=Path(__file__).resolve().parent
WEIGHTS=(0xb2,0x69,0x3c,0x87)
THRESHOLDS=(-2,0,2,4)


def scalar(x,w):
    return sum((2*(x>>i&1)-1)*(2*(w>>i&1)-1) for i in range(8))


def oracle():
    return bytes(sum((scalar(x,w)>=t)<<i for i,(w,t) in enumerate(zip(WEIGHTS,THRESHOLDS))) for x in range(256))


def build(yosys,router,root,*,units=("dot_unit","pop_unit"),source=None,expected=None,route_flags=()):
    raw={}
    if expected is None:
        expected=oracle()
    for unit in units:
        wd=root/unit
        wd.mkdir()
        for file in ("neurones.v","banc_neurones.v","neurones.pcf"):
            shutil.copyfile(HERE/file,wd/file)
        if source is not None:
            (wd/"neurones.v").write_text(source[unit],encoding="ascii")
        def ys(commands):
            (wd/"flow.ys").write_text("\n".join(commands),encoding="ascii")
            return run_command([yosys,"-s","flow.ys"],wd)
        src=f"read_verilog -DUNIT={unit} neurones.v"
        log=ys([src,"prep -top layer -flatten"]+[f"eval -set x {x} -show y" for x in range(256)])
        rtl=bytes(int(v,2) for v in re.findall(r"Eval result: .*?= 4'([01]{4})",log))
        assert rtl==expected
        ys([src,"synth_ice40 -device hx -top layer -json mapped.json","write_verilog -noattr -noexpr mapped.v"])
        mod=json.loads((wd/"mapped.json").read_text())["modules"]["layer"]
        mapped=dict(inputs=mod["ports"]["x"]["bits"],output=mod["ports"]["y"]["bits"],cells=read_cells(mod))
        ys(["read_verilog -lib -nowb +/ice40/cells_sim.v","read_verilog mapped.v banc_neurones.v",
            "hierarchy -top bench","flatten","opt_clean","write_json bench.json"])
        reg=registered_core(json.loads((wd/"bench.json").read_text())["modules"]["bench"],input_count=8,output_count=4)
        routes={}
        for seed in SEEDS:
            run_command([router,*route_flags,"--hx8k","--package","ct256","--json","bench.json","--pcf","neurones.pcf",
                         "--freq","100","--timing-allow-fail","--seed",str(seed),"--report","route.json"],wd)
            routes[str(seed)]=json.loads((wd/"route.json").read_text())
        raw[unit]=dict(rtl=hashlib.sha256(rtl).hexdigest(),mapped=mapped,registered=reg,routes=routes)
    return raw


def check(raw):
    expected=oracle()
    for x in range(256):
        for w in range(256):
            assert scalar(x,w)==2*(8-(x^w).bit_count())-8
    result={}
    for unit in ("dot_unit","pop_unit"):
        item=raw[unit]
        assert item["rtl"]==hashlib.sha256(expected).hexdigest()
        mapped=netcheck(item["mapped"],expected)
        assert netcheck(item["registered"],expected)==mapped
        routes=[path_stats(item["routes"][str(seed)]) for seed in SEEDS]
        result[unit]=dict(**mapped,routes=routes,median_ns=median(v["ns"] for v in routes))
    return dict(architecture=[8,4],weights=WEIGHTS,thresholds=THRESHOLDS,inputs=len(expected),
                elementary_dot_checks=65536,truth_sha256=hashlib.sha256(expected).hexdigest(),results=result)


if __name__=="__main__":
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument("--rebuild",nargs=2,metavar=("YOSYS","NEXTPNR"))
    p.add_argument("--export",type=Path)
    args=p.parse_args()
    if not __debug__:
        raise RuntimeError("Enable assertions")
    if args.rebuild:
        with tempfile.TemporaryDirectory() as tmp:
            raw=build(*args.rebuild,Path(tmp))
    else:
        raw=json.loads((HERE/"rapports-neurones.json").read_text())
    output=check(raw)
    if args.export:
        args.export.write_text(json.dumps(raw,separators=(",",":"))+"\n",encoding="utf8")
    print(json.dumps(output,indent=2))
