"""Fresh graph map, then controlled Grover/teleport comparison on the same QPU."""
import getpass
import json
import logging
import math
import random
import sys
import time
import traceback
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

import graph156
from switch_puzzles import ROOT, SHOTS, SEED, PARITIES, classical, circuit, score

MAP=ROOT/"Switch-puzzles-fresh-map.json"
TEST=ROOT/"Switch-puzzles-hardware.json"
BASE_TAG="switch-puzzles-20261120-v1"


def load(path):
    return json.loads(path.read_text()) if path.exists() else {}


def execute(service,backend,path,tag,rec,make):
    if rec.get("stage")=="done":
        return rec
    if rec.get("stage")=="failed":
        raise RuntimeError("Previously submitted job failed")
    if rec.get("job_id"):
        job=service.job(rec["job_id"])
    elif rec.get("stage")=="submitting":
        matches=service.jobs(job_tags=[tag],limit=2)
        if len(matches)!=1:
            raise RuntimeError("Prior submission must be reconciled")
        job=matches[0]
    else:
        circuits=make()
        sampler=SamplerV2(mode=backend,options={"max_execution_time":30,"environment":{"job_tags":[tag]},
                          "twirling":{"enable_measure":False,"enable_gates":False},
                          "dynamical_decoupling":{"enable":False}})
        rec.update(stage="submitting",tag=tag,shots_per_circuit=SHOTS)
        with path.open("x",encoding="utf8") as f:
            json.dump(rec,f,indent=2)
        job=sampler.run(circuits,shots=SHOTS)
    rec.update(stage="submitted",job_id=job.job_id())
    graph156.save(path,rec)
    pubs=job.result()
    rec["counts"]=[pub.data.c.get_counts() for pub in pubs]
    assert all(sum(c.values())==SHOTS for c in rec["counts"])
    for _ in range(24):
        metrics=job.metrics()
        if metrics.get("usage",{}).get("status")=="complete":
            break
        time.sleep(5)
    rec.update(stage="done",metrics=metrics)
    graph156.save(path,rec)
    return rec


def compile_map(b):
    p=b.properties(refresh=True)
    if p.faulty_qubits():
        raise ValueError("Processor has flagged faulty qubits")
    bad={tuple(sorted(g.qubits)) for g in p.faulty_gates() if len(g.qubits)==2}
    geo=graph156.geometry(e for e in b.coupling_map.get_edges() if tuple(sorted(e)) not in bad)
    isa=transpile(graph156.circuits(geo),b,initial_layout=list(range(156)),optimization_level=1,
                  seed_transpiler=SEED,num_processes=1,routing_method="none")
    for qc in isa:
        b.check_faulty(qc)
        edges=[sorted(qc.find_bit(q).index for q in op.qubits) for op in qc.data if len(op.qubits)==2]
        measured={qc.find_bit(op.clbits[0]).index:qc.find_bit(op.qubits[0]).index
                  for op in qc.data if op.operation.name=="measure"}
        assert sorted(edges)==geo["edges"] and measured==dict(enumerate(range(156)))
    return geo,isa


def compile_one(b,path,puzzle,mode,fast):
    q=circuit(puzzle,mode,fast)
    isa=transpile(q,b,initial_layout=list(path),optimization_level=1,routing_method="none",seed_transpiler=SEED)
    b.check_faulty(isa)
    measured={}
    flags=[]
    links=Counter()
    for op in isa.data:
        gate=op.operation
        physical=[isa.find_bit(q).index for q in op.qubits]
        if gate.name!="barrier":
            assert set(physical)<=set(path)
        if gate.name=="cz":
            a,c=sorted(path.index(x) for x in physical)
            assert c==a+1
            links[a]+=1
        if gate.name in ("measure","measure_2"):
            measured[isa.find_bit(op.clbits[0]).index]=physical[0]
        if gate.name=="if_else":
            bit,value=gate.condition
            flag=isa.find_bit(bit).index
            assert physical==[path[4]] and value==1 and flag in measured
            flags.append(flag)
    expected={2:path[0],1:path[1],0:path[2]}
    if mode=="teleport":
        expected.update({0:path[4],3:path[2],4:path[3]})
        assert flags==[4,3]
    assert measured==expected
    return isa,[links[i] for i in range(4)]


def paths_and_scores(b,geo,analysis):
    neighbors=[[] for _ in range(156)]
    err={}
    for a,c in geo["edges"]:
        prop=b.target["cz"].get((a,c)) or b.target["cz"].get((c,a))
        if prop is None or prop.error is None or not 0<=prop.error<1:
            continue
        neighbors[a].append(c)
        neighbors[c].append(a)
        err[a,c]=err[c,a]=prop.error
    def extend(path):
        if len(path)==5:
            yield tuple(path)
            return
        for q in neighbors[path[-1]]:
            if q not in path:
                yield from extend(path+[q])
    paths=[p for i in range(156) for p in extend([i])]
    # Common pulse basis and routing-free layout: edge counts are verified again on both paths.
    # Rank by a heuristic, not an estimated circuit fidelity.
    gate_weights=[0.]*4
    for puzzle in PARITIES:
        for mode in ("direct","teleport"):
            _,counts=compile_one(b,paths[0],puzzle,mode,False)
            gate_weights=[x+n/4 for x,n in zip(gate_weights,counts)]
    vertex=[-math.log((v+0.5)/(SHOTS+1)) for v in analysis["correct_by_qubit"]]
    ranked=sorted((sum(vertex[q] for q in path)+sum(w*-math.log1p(-err[e]) for w,e in zip(gate_weights,zip(path,path[1:]))),path) for path in paths)
    median=(ranked[(len(ranked)-1)//2][0]+ranked[len(ranked)//2][0])/2
    best=ranked[0]
    typical=min((entry for entry in ranked if set(entry[1]).isdisjoint(best[1])),
                key=lambda entry:(abs(entry[0]-median),entry))
    selected={}
    for label,entry in (("best",best),("typical",typical)):
        s,path=entry
        selected[label]={"path":list(path),"score":s,"rank":ranked.index(entry)+1,
                         "map_correct":[analysis["correct_by_qubit"][q] for q in path],
                         "edge_errors":[err[e] for e in zip(path,path[1:])]}
    return selected,{"candidate_count":len(ranked),"median_score":median,"cz_weights":gate_weights,
                     "method":"sum negative log smoothed graph pass rates plus native CZ workload weighted negative log CZ success"}


def run():
    if not (ROOT/"Switch-puzzles-simulator.json").exists() or not sys.stdin.isatty():
        raise RuntimeError("Simulate first and use a private console")
    if load(TEST).get("rows"):
        return
    token=getpass.getpass("IBM Cloud API key (hidden): ").strip()
    if not token:
        return
    service=QiskitRuntimeService(channel="ibm_quantum_platform",token=token,plans_preference=["open"],region="us-east")
    m=load(MAP)
    if m:
        b=service.backend(m["backend"])
        isa=None
    else:
        devices={b.name:b for b in service.backends(simulator=False,min_num_qubits=156) if not b.is_mock and b.num_qubits==156}
        prepared={}
        excluded={}
        while True:
            queues={n:b.status().to_dict() for n,b in devices.items()}
            active=[n for n,s in queues.items() if s["operational"] and s["status_msg"].lower()=="active" and n not in excluded]
            name=min(active,key=lambda n:(queues[n]["pending_jobs"],n))
            b=devices[name]
            if name in prepared:
                break
            try:
                prepared[name]=compile_map(b)
            except ValueError as e:
                excluded[name]=str(e)
        geo,isa=prepared[name]
        m={"backend":name,"queues":queues,"excluded":excluded,"geometry":geo,
           "queue_snapshot_utc":datetime.now(timezone.utc).isoformat()}
    m=execute(service,b,MAP,BASE_TAG+"-map",m,lambda:isa)
    analysis=graph156.analyze(m["geometry"],m["counts"])
    m["analysis"]=analysis
    graph156.save(MAP,m)
    rec=load(TEST)
    isa=[]
    if not rec:
        selected,ranking=paths_and_scores(b,m["geometry"],analysis)
        cells=[(l,p,mode) for l in selected for p in PARITIES for mode in ("direct","teleport")]
        random.Random(SEED).shuffle(cells)
        fast=all(b.target.instruction_supported("measure_2",(q,)) for s in selected.values() for q in s["path"][2:4])
        settings=[]
        weights={}
        for label,puzzle,mode in cells:
            q,links=compile_one(b,selected[label]["path"],puzzle,mode,fast)
            isa.append(q)
            settings.append({"chain":label,"puzzle":puzzle,"mode":mode,"native_cz_per_link":links})
            key=(puzzle,mode)
            if key in weights:
                assert weights[key]==links
            weights[key]=links
        assert ranking["cz_weights"]==[sum(v[i] for v in weights.values())/4 for i in range(4)]
        rec={"backend":b.name,"map_job":m["job_id"],"selected":selected,"ranking":ranking,
             "settings":settings,"mid_readout":"measure_2" if fast else "measure",
             "solutions_ABC":classical()}
    rec=execute(service,b,TEST,BASE_TAG+"-test",rec,lambda:isa)
    assert len(rec["counts"])==len(rec["settings"])==8
    rec["rows"]=[dict(s,correct=score(c,rec["solutions_ABC"][s["puzzle"]]))
                 for s,c in zip(rec["settings"],rec["counts"])]
    graph156.save(TEST,rec)
    print([(r["chain"],r["puzzle"],r["mode"],r["correct"]) for r in rec["rows"]])


if __name__=="__main__":
    logging.disable(logging.CRITICAL)
    try:
        run()
    except Exception as e:
        frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(e.__traceback__)]
        graph156.save(ROOT.parent/"work"/"switch-puzzles-error.json",{"type":type(e).__name__,"frames":frames})
        print(type(e).__name__)
    input("Press Enter to close.")
