"""Compare reading the teleported Hamming word at Bob and two SWAPs beyond Bob."""
import getpass
import logging
import sys
from collections import Counter, defaultdict

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime.fake_provider import FakeKingston

from graph156 import save
from hamming_ascii import VALUE, WIDTH, analyze, encode
from run_switch_puzzles import ROOT, SHOTS, execute, load
from teleport_ascii_a import SEED, circuit

HW = ROOT / "Charlie-A-Kingston.json"
SIM = ROOT / "Charlie-A-simulator.json"
STATUS = ROOT.parent / "work" / "charlie-status.json"
TAG = "charlie-two-swaps-ascii-a-kingston-20261120"
RECEIVERS = ("Bob", "Charlie")


def paths_for(backend):
    props = backend.properties()
    bad = set(props.faulty_qubits())
    blocked = {tuple(sorted(g.qubits)) for g in props.faulty_gates() if len(g.qubits) == 2}
    links = defaultdict(dict)
    for (a, b), gate in backend.target["cz"].items():
        if not (bad & {a, b}) and tuple(sorted((a, b))) not in blocked and gate and gate.error is not None:
            links[a][b] = links[b][a] = gate.error

    def extend(path):
        if len(path) == 5:
            yield path
        else:
            for nxt in links[path[-1]]:
                if nxt not in path:
                    yield from extend((*path, nxt))

    def cost(p):
        readout = sum(props.readout_error(q) for q in (p[0], p[1], p[2], p[4]))
        return readout + sum(weight * links[a][b] for weight, a, b in zip((1, 1, 3, 3), p, p[1:]))

    choices = sorted((p for q in links for p in extend((q,))), key=cost)
    previous = load(ROOT / "Hamming-A-Kingston.json")["triples_by_position"]
    selected = {}
    used = set()
    # Prefer an extension of the previous triple when the extra sites are free.
    for i, triple in enumerate(previous):
        candidates = (p for p in choices if p[:3] == tuple(triple) and used.isdisjoint(p))
        path = next(candidates, None)
        if path:
            selected[i] = path
            used.update(path)
    for i in range(WIDTH):
        if i not in selected:
            path = next(p for p in choices if used.isdisjoint(p))
            selected[i] = path
            used.update(path)
    return [selected[i] for i in range(WIDTH)]


def make(receiver, fast=False):
    template = circuit("teleport", fast, encode(VALUE), WIDTH)
    # Keep Alice's measurements, even though she never uses those wires again.
    for i in reversed(range(len(template.data))):
        inst = template.data[i]
        if inst.operation.name == "measure" and template.find_bit(inst.clbits[0]).index >= 2*WIDTH:
            del template.data[i]
    q = QuantumCircuit(5 * WIDTH, 3 * WIDTH, name=receiver)
    original = [5*i+j for i in range(WIDTH) for j in range(3)]
    q.compose(template, qubits=original, clbits=list(range(template.num_clbits)), inplace=True)
    for i in range(WIDTH):
        bob = 5*i+2
        endpoint = bob
        if receiver == "Charlie":
            q.swap(bob, bob+1)
            q.swap(bob+1, bob+2)
            endpoint = bob+2
        q.measure(endpoint, 2*WIDTH+i)
    return q


def compile_pair(backend, paths):
    fast = all(backend.target.instruction_supported("measure_2", (q,)) for p in paths for q in p[:2])
    layout = [q for p in paths for q in p]
    assert len(set(layout)) == 5*WIDTH
    result = []
    for receiver in RECEIVERS:
        q = transpile(make(receiver, fast), backend, initial_layout=layout, optimization_level=0,
                      routing_method="none", seed_transpiler=SEED, num_processes=1)
        backend.check_faulty(q)
        measured = {}
        edges = Counter()
        for inst in q.data:
            physical = tuple(q.find_bit(w).index for w in inst.qubits)
            if inst.operation.name in ("measure", "measure_2"):
                measured[q.find_bit(inst.clbits[0]).index] = physical[0]
            if inst.operation.name == "cz":
                edges[tuple(sorted(physical))] += 1
        expected = {2*i+j: p[j] for i, p in enumerate(paths) for j in (0, 1)}
        expected.update({2*WIDTH+i: p[2 if receiver == "Bob" else 4] for i, p in enumerate(paths)})
        expected_edges = Counter()
        for p in paths:
            for j, n in enumerate((1, 1) if receiver == "Bob" else (1, 1, 3, 3)):
                expected_edges[tuple(sorted(p[j:j+2]))] = n
        assert measured == expected and edges == expected_edges
        result.append(q)
    return result


def simulate():
    sim = AerSimulator(method="stabilizer")
    results = sim.run([make(r) for r in RECEIVERS], shots=SHOTS, seed_simulator=SEED).result()
    rows = {r: analyze(results.get_counts(i)) for i, r in enumerate(RECEIVERS)}
    assert all(v["raw_byte_exact"] == v["decoded_byte_exact"] == SHOTS for v in rows.values())
    device = FakeKingston()
    compiled = compile_pair(device, paths_for(device))
    save(SIM, dict(shots=SHOTS, analysis=rows, verified_native_cz=[q.count_ops()["cz"] for q in compiled]))
    print({r: row["decoded_byte_exact"] for r, row in rows.items()})


def hardware():
    rec = load(HW)
    if rec.get("analysis"):
        return
    assert SIM.exists()
    save(STATUS, {"stage": "waiting for private key"})
    key = getpass.getpass("IBM Cloud API key for Kingston (hidden): ").strip()
    if not key:
        save(STATUS, {"stage": "cancelled before login"})
        return
    save(STATUS, {"stage": "connecting"})
    service = QiskitRuntimeService(channel="ibm_quantum_platform", token=key, plans_preference=["open"], region="us-east")
    backend = service.backend("ibm_kingston")
    circuits = []
    if not rec:
        paths = paths_for(backend)
        circuits = compile_pair(backend, paths)
        rec = dict(backend=backend.name, receivers=RECEIVERS, paths_by_hamming_position=paths,
                   native_counts=[dict(q.count_ops()) for q in circuits])
    rec = execute(service, backend, HW, TAG, rec, lambda: circuits)
    rec["analysis"] = {r: analyze(counts) for r, counts in zip(RECEIVERS, rec["counts"], strict=True)}
    save(HW, rec)
    save(STATUS, {"stage": "finished"})


if __name__ == "__main__":
    if sys.argv[1:] == ["simulate"]:
        simulate()
    elif sys.argv[1:] == ["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            import traceback
            save(STATUS, {"stage": "error", "type": type(exc).__name__,
                          "frames": [f.name for f in traceback.extract_tb(exc.__traceback__)]})
            print(type(exc).__name__)
            input("Press Enter to close.")
