"""Score Kingston's original compiled teleport instructions with stock Mapomatic."""
import json
import math
from pathlib import Path
import sys
from types import SimpleNamespace
import warnings

from qiskit import QuantumCircuit
from qiskit_ibm_runtime.models import BackendProperties

ROOT=Path(__file__).resolve().parent
sys.path.insert(0,str(ROOT/"tmp/mapomatic-package"))
import mapomatic as mm

def read(path):
    return json.loads((ROOT/path).read_bytes())

def run():
    data=read("Neighbor-Kingston.json")
    fresh=read("Neighbor-fresh-map.json")
    raw=read("tmp/mapomatic-properties.json")
    if (ROOT/"tmp/mapomatic-job-ops.json").exists():
        ops=read("tmp/mapomatic-job-ops.json")
        circuit_source="IBM job.inputs"
    else:
        # Recompile with the original experiment's physical layouts and seed.
        from qiskit_ibm_runtime.fake_provider import FakeKingston
        from neighboring_teleports import prepare,inputs
        device=FakeKingston()
        ops={}
        for case,expected in data["native_counts"].items():
            active=inputs(case)
            paths=[data["selection"]["AB"[i]] for i,bit in active]
            value=sum(bit<<j for j,(_,bit) in enumerate(active))
            _,_,circs=prepare(device,paths,("teleport",),value)
            circ=circs[0]
            assert dict(circ.count_ops())==expected
            ops[case]=[[i.operation.name,[circ.find_bit(q).index for q in i.qubits]]
                       for i in circ.data if i.operation.name!="barrier"]
        circuit_source="Locally reconstructed using the original prepare routine, seed and verified physical paths; all 8 native gate tallies matched the recorded job."
    props=BackendProperties.from_dict(raw)
    backend=SimpleNamespace(properties=lambda:props,configuration=lambda:SimpleNamespace(basis_gates=["rz","sx","x","cz"]))
    routes={r:tuple(data["selection"][r]) for r in "AB"}
    edges={tuple(e) for e in fresh["geometry"]["edges"] if 0 <= props.gate_error("cz",e) < 1}
    hits=fresh["analysis"]["correct_by_qubit"]

    def template(case,route):
        path=routes[route]
        q=QuantumCircuit(3,3)
        for gate,physical in ops[case]:
            if not set(physical).intersection(path):
                continue
            assert set(physical)<=set(path)
            wires=[path.index(w) for w in physical]
            if gate=="measure":
                q.measure(wires[0],wires[0])
            elif gate in ("x","sx","cz"):
                getattr(q,gate)(*wires)
            else:
                # These single-wire operations contribute no factor in stock default_cost.
                assert gate in ("if_else","measure_2","rz") and len(wires)==1
        return q

    def scores(q,layouts):
        return {tuple(p):cost for p,cost in mm.evaluate_layouts(q,[list(p) for p in layouts],backend)}

    layouts=mm.matching_layouts(template("0-","A"),[list(e) for e in edges],strict_direction=False)
    assert len(set(map(tuple,layouts)))==len(layouts)
    per_route={}
    ranked={}
    solo_scores={}
    for r in "AB":
        cases=("0-","1-") if r=="A" else ("-0","-1")
        by_bit=[scores(template(case,r),layouts) for case in cases]
        avg={p:sum(s[p] for s in by_bit)/2 for p in by_bit[0]}
        ranked[r]=avg
        p=routes[r]
        solo_scores[r]=[s[p] for s in by_bit]
        joint_costs=[]
        for case in ("00","01","10","11"):
            x=scores(template(case,r),[p])[p]
            assert math.isclose(x,solo_scores[r][int(case["AB".index(r)])],abs_tol=1e-12)
            joint_costs.append(x)
        per_route[r]=dict(path=p,solo_costs_0_1=solo_scores[r],joint_costs_00_01_10_11=joint_costs,
                          mean_cost=avg[p],rank=1+sum(cost<avg[p]-1e-12 for cost in avg.values()),
                          graph_pass_fraction=sum(hits[i] for i in p)/(3*256),
                          accuracy_alone=data["contrasts"][r]["alone"]/512,
                          accuracy_together=data["contrasts"][r]["together"]/1024)
    pairs=[]
    for a,ca in ranked["A"].items():
        for b,cb in ranked["B"].items():
            if (a[-1],b[-1]) in edges and set(a).isdisjoint(b):
                pairs.append((1-(1-ca)*(1-cb),a,b))
    pairs.sort()
    assert len(pairs)==data["selection"]["candidate_pairs"]
    paired=next(x for x in pairs if x[1:]==(routes["A"],routes["B"]))
    best=pairs[0]
    out=dict(package="mapomatic",version=mm.__version__,method="Stock evaluate_layouts default cost, equal weighting of inputs; scored projection of native instructions",
             omitted="Stock cost ignores single-wire if_else, measure_2 and rz. No idle or simultaneous-neighbor error term.",
             job=data["job_id"],running_utc=data["metrics"]["timestamps"]["running"],calibration=raw["last_update_date"],
             circuit_source=circuit_source,calibration_source="IBM job.properties()",n_oriented_routes=len(layouts),
             routes=per_route,n_adjacent_disjoint_pairs=len(pairs),original_pair_cost=paired[0],
             original_pair_rank=1+sum(x[0]<paired[0]-1e-12 for x in pairs),
             best_pair={"A":best[1],"B":best[2],"cost":best[0]})
    (ROOT/"Mapomatic-Kingston-baseline.json").write_text(json.dumps(out,indent=2))
    print(json.dumps(out,indent=2))

if __name__=="__main__":
    warnings.filterwarnings("ignore",category=DeprecationWarning,module="mapomatic")
    run()
