"""Transfer the eight bits of ASCII A in parallel and score Bob's whole byte."""
import getpass
import logging
import sys
import traceback
from collections import Counter
from pathlib import Path

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

from graph156 import save
from run_switch_puzzles import ROOT, SHOTS, execute, load

VALUE = ord("A")
MODES = ("teleport", "direct")
SEED = 20261121
SIM = ROOT/"ASCII-A-simulator.json"
HW = ROOT/"ASCII-A-Kingston.json"
TAG = "ascii-A-8-triples-kingston-20261120"


def circuit(mode, fast=False, value=VALUE, width=8):
    q = QuantumCircuit(3*width,3*width,name="ascii_"+mode)
    for i in range(width):
        src, alice, bob = range(3*i,3*i+3)
        if (value>>i)&1:
            q.x(src if mode=="teleport" else bob)
        if mode=="teleport":
            q.h(alice)
            q.cx(alice,bob)
            q.cx(src,alice)
            q.h(src)
    if mode=="teleport":
        for i in range(width):
            for role in (0,1):
                wire,flag = 3*i+role,2*i+role
                if fast:
                    q.append(MidCircuitMeasure(),[wire],[flag])
                else:
                    q.measure(wire,flag)
        for i in range(width):
            with q.if_test((q.clbits[2*i+1],1)):
                q.x(3*i+2)
            with q.if_test((q.clbits[2*i],1)):
                q.z(3*i+2)
        q.barrier()
    for i in range(width):
        q.measure(3*i+2,2*width+i)
    return q


def analyze(counts):
    byte_counts=Counter()
    for word,n in counts.items():
        assert len(word)==24 and set(word)<={"0","1"}
        byte_counts[word[:8]]+=n
    assert sum(byte_counts.values())==SHOTS
    return {"byte_counts":dict(byte_counts),"exact":byte_counts[format(VALUE,"08b")]}


def simulate():
    sim=AerSimulator(method="stabilizer")
    result=sim.run([circuit(m) for m in MODES],shots=SHOTS,seed_simulator=SEED).result()
    counts=result.get_counts()
    rows=[analyze(c) for c in counts]
    assert all(row["exact"]==SHOTS for row in rows)
    for i in range(8):
        assert {((int(w,2)>>(2*i))&3) for w in counts[0]}==set(range(4))
    save(SIM,{"modes":MODES,"shots_per_circuit":SHOTS,"input_byte":"01000001","seed":SEED,"rows":rows})
    print([row["exact"] for row in rows])


def triples(backend, count=8, reserved=()):
    props=backend.properties(refresh=True)
    bad=set(props.faulty_qubits())
    bad_edges={tuple(sorted(g.qubits)) for g in props.faulty_gates() if len(g.qubits)==2}
    neighbors={i:{} for i in range(backend.num_qubits) if i not in bad}
    for u,v in backend.coupling_map.get_edges():
        if u in bad or v in bad or tuple(sorted((u,v))) in bad_edges:
            continue
        entry=backend.target["cz"].get((u,v)) or backend.target["cz"].get((v,u))
        if entry is not None and entry.error is not None:
            neighbors[u][v]=neighbors[v][u]=entry.error
    candidates=[]
    for alice,links in neighbors.items():
        for src in links:
            for bob in links:
                if src>=bob:
                    continue
                path=(src,alice,bob)
                cost=sum(props.readout_error(i) for i in path)+links[src]+links[bob]
                candidates.append((cost,path))
    used=set(reserved)
    result=[]
    for _,path in sorted(candidates):
        if used.isdisjoint(path):
            result.append(path)
            used.update(path)
        if len(result)==count:
            return result
    raise ValueError("Could not place the requested disjoint triples")


def prepare(backend, paths=None, modes=MODES, value=VALUE):
    paths=triples(backend) if paths is None else paths
    width=len(paths)
    layout=[w for path in paths for w in path]
    fast=all(backend.target.instruction_supported("measure_2",(w,)) for path in paths for w in path[:2])
    isa=transpile([circuit(m,fast,value,width) for m in modes],backend,initial_layout=layout,
                  routing_method="none",optimization_level=1,seed_transpiler=SEED,num_processes=1)
    for mode,q in zip(modes,isa):
        backend.check_faulty(q)
        measured={}
        controls=[]
        edges=[]
        for op in q.data:
            g=op.operation
            wires=[q.find_bit(w).index for w in op.qubits]
            if g.name!="barrier":
                assert set(wires)<=set(layout if mode=="teleport" else layout[2::3])
            if g.name in ("measure","measure_2"):
                measured[q.find_bit(op.clbits[0]).index]=wires[0]
            if g.name=="if_else":
                bit,val=g.condition
                assert val==1
                controls.append((q.find_bit(bit).index,wires[0]))
            if g.name=="cz":
                edges.append(tuple(sorted(wires)))
        expected={2*width+i:p[2] for i,p in enumerate(paths)}
        if mode=="teleport":
            expected.update({2*i+j:p[j] for i,p in enumerate(paths) for j in (0,1)})
        assert measured==expected
        assert sorted(controls)==([(2*i+j,p[2]) for i,p in enumerate(paths) for j in (0,1)] if mode=="teleport" else [])
        assert sorted(edges)==(sorted(tuple(sorted(e)) for p in paths for e in (p[:2],p[1:])) if mode=="teleport" else [])
    return paths,fast,isa


def hardware():
    rec=load(HW)
    if rec.get("rows"):
        return
    if not sys.stdin.isatty() or not SIM.exists():
        raise RuntimeError("Run simulator first and use an interactive key prompt")
    while True:
        key=getpass.getpass("IBM Cloud API key (hidden): ").strip()
        if not key:
            return
        try:
            service=QiskitRuntimeService(channel="ibm_quantum_platform",token=key,plans_preference=["open"],region="us-east")
            break
        except InvalidAccountError:
            print("IBM instance lookup failed. Paste the key again or press Enter to exit.")
    backend=service.backend("ibm_kingston")
    isa=[]
    if not rec:
        paths,fast,isa=prepare(backend)
        rec=dict(backend=backend.name,modes=MODES,triples_from_least_significant_bit=paths,
                 fast_mid_measure=fast,input_byte="01000001",native_counts=[dict(q.count_ops()) for q in isa])
    rec=execute(service,backend,HW,TAG,rec,lambda:isa)
    assert len(rec["counts"])==2
    rec["rows"]=[analyze(c) for c in rec["counts"]]
    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"/"ascii-a-error.json",{"type":type(exc).__name__,"frames":frames})
            print(type(exc).__name__)
        input("Press Enter to close.")
