"""Teleport a bit-flip repetition code, measure both checks, and switch repair on or off."""
import getpass
import heapq
import itertools
import json
import logging
import math
from pathlib import Path
from collections import Counter
import random
import sys
import time
import traceback

from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
from qiskit_ibm_runtime.circuit import MidCircuitMeasure
from qiskit_ibm_runtime.accounts.exceptions import InvalidAccountError

from graph156 import ROOT, save

SHOTS, SEED = 256, 20317
SIM, HW = ROOT/"Checksum-teleport-simulator.json", ROOT/"Checksum-teleport-Kingston.json"
TAG="three-rail-teleport-checksum-20261120-v1"
LOGICAL={"source":[0,1,2],"alice":[3,4,5],"bob":[6,7,8],"checks":[9,10],
         "encode":[(1,0),(1,2)]}


def circuit(layout, bit, correct, fast=False, inject=None):
    used=sorted(set(layout["source"]+layout["alice"]+layout["bob"]+layout["checks"]+
                    [j for edge in layout["encode"] for j in edge]))
    q=QuantumRegister(len(used),"q")
    a,s,b=ClassicalRegister(6,"a"),ClassicalRegister(2,"s"),ClassicalRegister(3,"b")
    qc=QuantumCircuit(q,a,s,b)
    wire={p:q[i] for i,p in enumerate(used)}
    src,alice,bob,anc=[[wire[i] for i in layout[key]] for key in ("source","alice","bob","checks")]
    if bit:
        qc.x(src[1])
    for u,v in layout["encode"]:
        qc.cx(wire[u],wire[v])
    qc.barrier()
    for i in range(3):
        qc.h(alice[i])
        qc.cx(alice[i],bob[i])
        qc.cx(src[i],alice[i])
        qc.h(src[i])
    def read(w,c):
        if fast:
            qc.append(MidCircuitMeasure(),[w],[c])
        else:
            qc.measure(w,c)
    for i in range(3):
        read(src[i],a[2*i])
        read(alice[i],a[2*i+1])
    for i in range(3):
        with qc.if_test((a[2*i+1],1)):
            qc.x(bob[i])
        with qc.if_test((a[2*i],1)):
            qc.z(bob[i])
    qc.barrier()
    if inject is not None:
        qc.x(bob[inject])
    for i in range(2):
        qc.cx(bob[i],anc[i])
        qc.cx(bob[i+1],anc[i])
    for i in range(2):
        read(anc[i],s[i])
    if correct:
        for i,syndrome in enumerate((1,3,2)):
            with qc.if_test((s,syndrome)):
                qc.x(bob[i])
    qc.barrier()
    qc.measure(bob,b)
    return qc,used


def summarize(counts,bit):
    assert sum(counts.values())==SHOTS and all(len(w)==11 for w in counts)
    result={"bit_correct":0,"whole_word_correct":0,"syndromes":[0]*4}
    for w,n in counts.items():
        result["bit_correct"]+=n*(int(w[1])==bit)
        result["whole_word_correct"]+=n*(w[:3]==str(bit)*3)
        result["syndromes"][int(w[3:5],2)]+=n
    return result


def simulate():
    sim=AerSimulator(method="stabilizer")
    cases=list(itertools.product((0,1),(False,True),(None,0,1,2)))
    qs=[circuit(LOGICAL,bit,correct,inject=inj)[0] for bit,correct,inj in cases]
    counts=sim.run(qs,shots=SHOTS,seed_simulator=SEED).result().get_counts()
    rows=[]
    for (bit,correct,inj),raw in zip(cases,counts):
        c={w.replace(" ",""):n for w,n in raw.items()}
        out=summarize(c,bit)
        assert out["bit_correct"]==SHOTS*(correct or inj!=1)
        assert out["whole_word_correct"]==SHOTS*(correct or inj is None)
        assert out["syndromes"][0 if inj is None else (1,3,2)[inj]]==SHOTS
        rows.append(dict(bit=bit,correct=correct,injected_flip=inj,**out))
    save(SIM,{"model":"ideal Aer stabilizer","shots_each":SHOTS,"rows":rows})
    print("Verified both bits, both correction modes, clean and each single flip.")


def choose_layout(backend):
    props=backend.properties(refresh=True)
    excluded=set(props.faulty_qubits())
    bad_edges={tuple(sorted(g.qubits)) for g in props.faulty_gates() if len(g.qubits)==2}
    adj={i:set() for i in range(backend.num_qubits) if i not in excluded}
    err={}
    for u,v in backend.coupling_map.get_edges():
        if u not in adj or v not in adj or tuple(sorted((u,v))) in bad_edges:
            continue
        g=backend.target["cz"].get((u,v)) or backend.target["cz"].get((v,u))
        if g is not None and g.error is not None and g.error<1:
            err[u,v]=err[v,u]=-math.log1p(-g.error)
            adj[u].add(v)
            adj[v].add(u)
    readerr={i:-math.log(max(1e-8,1-props.readout_error(i))) for i in adj}
    def paths(p):
        if len(p)==5:
            if p[0]<p[-1]:
                yield p
            return
        for v in sorted(adj[p[-1]]-set(p)):
            yield from paths(p+[v])
    best=None
    for start in sorted(adj):
        for spine in paths([start]):
            bob=spine[::2]
            spine_set=set(spine)
            for alice in itertools.product(*(sorted(adj[i]-spine_set) for i in bob)):
                if len(set(alice))!=3:
                    continue
                reserved=spine_set|set(alice)
                for src in itertools.product(*(sorted(adj[i]-reserved) for i in alice)):
                    if len(set(src))!=3:
                        continue
                    # Grow a short encoding tree without touching Bob's data qubits.
                    root=src[1]
                    parent={root:None}
                    queue=[(0.,root,None)]
                    visited=set()
                    while queue and not set(src)<=visited:
                        dist,x,prev=heapq.heappop(queue)
                        if x in visited:
                            continue
                        visited.add(x)
                        parent[x]=prev
                        for v in adj[x]-visited-set(bob):
                            heapq.heappush(queue,(dist+.01+err[x,v],v,x))
                    if not set(src)<=visited:
                        continue
                    forward=[]
                    for end in (src[0],src[2]):
                        branch=[]
                        while parent[end] is not None:
                            branch.append((parent[end],end))
                            end=parent[end]
                        for edge in reversed(branch):
                            if edge not in forward:
                                forward.append(edge)
                    encode=forward+[e for e in reversed(forward) if e[1] not in src]
                    links=encode+list(zip(alice,bob))+list(zip(src,alice))+list(zip(spine,spine[1:]))
                    score=sum(.003+err[e] for e in links)+sum(readerr[i] for i in list(src)+list(alice)+spine)
                    if best is None or score<best[0]:
                        best=(score,dict(source=list(src),alice=list(alice),bob=bob,checks=spine[1::2],encode=encode))
    if best is None:
        raise RuntimeError("No connected layout")
    layout=best[1]
    ones={layout["source"][1]}
    for u,v in layout["encode"]:
        if u in ones:
            ones.symmetric_difference_update({v})
    assert ones==set(layout["source"])
    return layout


def prepare(backend,layout):
    measured_mid=layout["source"]+layout["alice"]+layout["checks"]
    fast=all(backend.target.instruction_supported("measure_2",(q,)) for q in measured_mid)
    cases=list(itertools.product((0,1),(False,True)))
    random.Random(SEED).shuffle(cases)
    compiled=[]
    details=[]
    for bit,correct in cases:
        q,used=circuit(layout,bit,correct,fast)
        isa=transpile(q,backend,initial_layout=used,routing_method="none",optimization_level=1,seed_transpiler=SEED)
        backend.check_faulty(isa)
        measured={}
        branches=[]
        for op in isa.data:
            physical=[isa.find_bit(w).index for w in op.qubits]
            assert op.operation.name=="barrier" or set(physical)<=set(used)
            if op.operation.name in ("measure","measure_2"):
                measured[isa.find_bit(op.clbits[0]).index]=physical[0]
            if op.operation.name=="if_else":
                test,value=op.operation.condition
                which=("s" if isinstance(test,ClassicalRegister) and test.name=="s" else isa.find_bit(test).index)
                branches.append((which,value,physical[0],op.operation.blocks[0].data[0].operation.name))
        expected={i:w for i,w in enumerate([v for pair in zip(layout["source"],layout["alice"]) for v in pair]+layout["checks"]+layout["bob"])}
        assert measured==expected
        assert [(k,v,p) for k,v,p,_ in branches]==[(j,1,layout["bob"][i]) for i in range(3) for j in (2*i+1,2*i)]+(
            [("s",v,p) for v,p in zip((1,3,2),layout["bob"])] if correct else [])
        compiled.append(isa)
        details.append(dict(bit=bit,correct=correct,native_counts=dict(isa.count_ops())))
    return compiled,details,fast,used


def hardware():
    if not sys.stdin.isatty() or not SIM.exists():
        raise RuntimeError("Use the private prompt after simulation")
    rec=json.loads(HW.read_text()) if HW.exists() else {}
    if rec.get("stage")=="done":
        return
    while True:
        key=getpass.getpass("IBM Cloud API key (hidden; Enter alone to exit): ").strip()
        if not key:
            return
        try:
            service=QiskitRuntimeService(channel="ibm_quantum_platform",token=key,plans_preference=["open"],region="us-east")
            break
        except InvalidAccountError as exc:
            cause=exc.__cause__
            print("IBM instance lookup failed.",type(cause).__name__,"HTTP status",getattr(cause,"code",None),
                  "Paste the key again or press Enter to exit.")
    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("Reconcile prior submission")
        job=matches[0]
    else:
        backend=service.backend("ibm_kingston")
        layout=choose_layout(backend)
        compiled,details,fast,used=prepare(backend,layout)
        rec=dict(stage="submitting",backend=backend.name,layout=layout,used=used,cases=details,
                 fast_mid_measure=fast,shots_per_case=SHOTS,tag=TAG,primary="Bob center rail after optional physical repair")
        sampler=SamplerV2(mode=backend,options={"max_execution_time":30,"environment":{"job_tags":[TAG]},
                          "twirling":{"enable_gates":False,"enable_measure":False},"dynamical_decoupling":{"enable":False}})
        with HW.open("x",encoding="utf8") as f:
            json.dump(rec,f,indent=2)
        job=sampler.run(compiled,shots=SHOTS)
    rec.update(stage="submitted",job_id=job.job_id())
    save(HW,rec)
    pubs=job.result()
    assert len(pubs)==4
    rec["counts"]=[dict(Counter(b+s+a for b,s,a in zip(pub.data.b.get_bitstrings(),
                          pub.data.s.get_bitstrings(),pub.data.a.get_bitstrings()))) for pub in pubs]
    rec["rows"]=[dict(case,**summarize(c,case["bit"])) for case,c in zip(rec["cases"],rec["counts"])]
    rec.update(stage="measured",bit_order="b2 b1 b0 | s1 s0 | a5 ... a0")
    save(HW,rec)
    for _ in range(120):
        metrics=job.metrics()
        if metrics.get("usage",{}).get("status")=="complete":
            break
        time.sleep(5)
    rec.update(stage="done",metrics=metrics)
    save(HW,rec)


if __name__=="__main__":
    if sys.argv[1:]==["simulate"]:
        simulate()
    elif sys.argv[1:]==["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]
            save(ROOT.parent/"work"/"checksum-teleport-error.json",dict(type=type(exc).__name__,frames=frames))
            print(type(exc).__name__)
        input("Press Enter to close.")
