"""Combinational equivalence and paired register-to-register timing, iCE40 HX8K."""
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import subprocess
import sys

from graphe18 import run, verilog

PAIRS = [(3, 5), (5, 10), (9, 11), (11, 14)]
PINS = "J3 C16 B16 D14 D15 D16 E14 F15 G15 B5 B4 A2 A1".split()


def design(x, y):
    modules = [verilog(x, y)]
    for label, coef in [('left', x), ('right', y)]:
        modules.append(verilog(coef, coef).split('module direct')[0].replace('module shared', 'module '+label))
    modules.append("module separate(input [3:0] x, output [3:0] a,b); left l(x,a,); right r(x,b,); endmodule")
    return "\n".join(modules)


def measure(yosys, router):
    rows = []
    for x, y in PAIRS:
        with TemporaryDirectory() as tmp:
            work = Path(tmp)
            ports = ['clk'] + [f'x[{i}]' for i in range(4)] + [f'y[{i}]' for i in range(8)]
            (work/'pins.pcf').write_text(''.join(f'set_io {port} {pin}\n' for port,pin in zip(ports,PINS)))
            rtl = design(x,y)
            for core in ('shared','separate'):
                wrapper = (f'module bench(input clk,input [3:0] x,output reg [7:0] y); reg [3:0] launch; '
                           f'wire [7:0] z; {core} core(launch,z[3:0],z[7:4]); '
                           'always @(posedge clk) begin launch<=x; y<=z; end endmodule')
                (work/'design.v').write_text(rtl+'\n'+wrapper)
                def synth(script):
                    subprocess.run([yosys,'-q','-p','read_verilog design.v; '+script],cwd=work,check=True)
                synth(f'miter -equiv -flatten direct {core} m; hierarchy -top m; sat -verify -prove trigger 0 m')
                synth('synth_ice40 -device hx -top bench -json net.json')
                for seed in (1,2,3):
                    subprocess.run([router,'--hx8k','--package','ct256','--json','net.json','--pcf','pins.pcf',
                                    '--freq','100','--seed',str(seed),'--timing-allow-fail','--report','r.json'],
                                   cwd=work,check=True,capture_output=True)
                    report=json.loads((work/'r.json').read_bytes())
                    clock,timing=next(iter(report['fmax'].items()))
                    path,=[p['path'] for p in report['critical_paths'] if p['from']==p['to']=='posedge '+clock]
                    ns=sum(a['delay'] for a in path)
                    assert abs(ns-1000/timing['achieved'])<.02 and timing['constraint']==100
                    rows.append(dict(x=x,y=y,core=core,ops=run(x,y)[core],seed=seed,
                                     ns=round(ns,3),lc=report['utilization']['ICESTORM_LC']['used']))
    versions=[]
    for exe,flag in [(yosys,'-V'),(router,'--version')]:
        info=subprocess.run([exe,flag],capture_output=True,text=True,check=True)
        versions.append((info.stdout+info.stderr).strip())
    return dict(target="HX8K-CT256",MHz=100,versions=versions,rows=rows)


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