"""Paired routing of the registered (7x,11x) mod 16 core; same pins and seeds."""
import json
from pathlib import Path
import subprocess
import sys
import tempfile
from graphe18 import verilog


def measure(yosys,router):
    pins=["J3","C16","B16","D14","D15","D16","E14","F15","G15","B5","B4","A2","A1"]
    ports=["clk"]+[f"x[{i}]" for i in range(4)]+[f"y[{i}]" for i in range(8)]
    rows=[]
    with tempfile.TemporaryDirectory() as tmp:
        directory=Path(tmp)
        (directory/"pins.pcf").write_text("".join(f"set_io {port} {pin}\n" for port,pin in zip(ports,pins)))
        for top in ("direct","shared"):
            wrapper=("module bench(input clk,input [3:0] x,output reg [7:0] y);"
                     "reg [3:0] launch; wire [7:0] result; "
                     f"{top} core(launch,result[3:0],result[7:4]); "
                     "always @(posedge clk) begin launch<=x; y<=result; end endmodule")
            (directory/"design.v").write_text(verilog(7,11)+"\n"+wrapper)
            subprocess.run([yosys,"-q","-p","read_verilog design.v; synth_ice40 -device hx -top bench -json net.json"],
                           cwd=directory,check=True)
            for seed in (1,2,3,4,5):
                cmd=[router,"--hx8k","--package","ct256","--json","net.json","--pcf","pins.pcf",
                     "--freq","100","--seed",str(seed),"--timing-allow-fail","--report","report.json"]
                subprocess.run(cmd,cwd=directory,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,check=True)
                data=json.loads((directory/"report.json").read_bytes())
                clock,timing=next(iter(data["fmax"].items()))
                paths=[p['path'] for p in data['critical_paths'] if p['from']==p['to']=='posedge '+clock]
                assert len(paths)==1 and timing['constraint']==100
                ns=sum(arc['delay'] for arc in paths[0])
                assert abs(ns-1000/timing['achieved'])<.02
                rows.append(dict(core=top,seed=seed,ns=round(ns,3),lc=data["utilization"]["ICESTORM_LC"]["used"]))
    version=subprocess.run([router,"--version"],capture_output=True,text=True,check=True)
    return dict(target="HX8K-CT256",router=(version.stdout+version.stderr).strip(),rows=rows)


if __name__=="__main__":
    print(json.dumps(measure(*sys.argv[1:]),indent=2))
