"""Six-qubit singlet teleportation: ideal dynamic simulation and one resumable Fez job."""

import getpass
import json
import logging
import sys
import time
import traceback
from datetime import datetime, timezone
from importlib.metadata import version
from pathlib import Path

from fez_singlet import circuit
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
from collections import defaultdict

ROOT = Path(__file__).resolve().parent
LOCAL = ROOT / "Fez-selected-singlet-simulator.json"
RESULT = ROOT / "Fez-selected-singlet-results.json"
TAG = "fez-selected-singlet-xyz-20261119"
SETTINGS = ["X", "Y", "Z"]
ORIGINAL = [21, 22, 23, 24, 25, 26]
SHOTS = 256
SEED = 2126


def save(path, record):
    temp = path.with_suffix(".tmp")
    temp.write_text(json.dumps(record, indent=2, default=str), encoding="utf-8")
    temp.replace(path)


def score(rows):
    if len(rows) != len(SETTINGS):
        raise ValueError("Missing circuit results")
    counts, endpoints, correct = {}, {}, {}
    for setting, row in zip(SETTINGS, rows):
        if sum(row.values()) != SHOTS or any(len(k) != 6 or set(k) - {"0", "1"} for k in row):
            raise ValueError("Unexpected outcomes or number of shots")
        counts[setting] = row
        pair = dict.fromkeys(("00", "01", "10", "11"), 0)
        for bits, n in row.items():
            pair[bits[-1] + bits[0]] += n
        endpoints[setting] = pair
        correct[setting] = pair["01"] + pair["10"]
    correlations = {axis: 1 - 2 * n / SHOTS for axis, n in correct.items()}
    fidelity = (1 - sum(correlations.values())) / 4
    # Independent binomial sampling of the three signed parity means.
    variance = sum((1 - c*c) / (SHOTS - 1) for c in correlations.values()) / 16
    return {"joint_counts": counts, "endpoint_counts_left_right": endpoints, "expected_parity_counts": correct,
            "correct": sum(correct.values()), "total": len(SETTINGS) * SHOTS, "shots_per_setting": SHOTS,
            "raw_bit_order": "c5..c0 correspond to the chain in reverse order",
            "target": "Psi minus", "correlations": correlations, "fidelity": fidelity,
            "fidelity_sampling_se": variance**0.5}


def simulate():
    sim = AerSimulator(method="stabilizer")
    result = sim.run([circuit(s) for s in SETTINGS], shots=SHOTS, seed_simulator=SEED).result()
    record = score(result.get_counts())
    if record["correct"] != record["total"]:
        raise ValueError("Ideal teleportation failed")
    for row in record["joint_counts"].values():
        if len({bits[1:-1] for bits, n in row.items() if n}) != 16:
            raise ValueError("Simulation missed a feed-forward branch")
    save(LOCAL, dict(record, simulator="Qiskit Aer stabilizer", seed=SEED,
                     versions={p: version(p) for p in ("qiskit", "qiskit-aer")}))
    print(record["expected_parity_counts"])


def select_chain(props, faulty_qubits, faulty_gates):
    rates = {}
    adj = defaultdict(set)
    bad = {(g["gate"], tuple(g["qubits"])) for g in faulty_gates}
    for gate in props["gates"]:
        name, qs = gate["gate"], tuple(gate["qubits"])
        if name not in ("cz", "measure", "measure_2") or (name, qs) in bad or set(qs).intersection(faulty_qubits):
            continue
        rate = next((p["value"] for p in gate["parameters"] if p["name"] == "gate_error"), None)
        if rate is None:
            continue
        rates[name, qs] = rate
        if name == "cz":
            adj[qs[0]].add(qs[1])

    def candidates(path):
        if len(path) < 6:
            for q in adj[path[-1]].difference(path):
                yield from candidates(path + [q])
        elif path[0] < path[-1]:
            gates = [rates["cz", (a,b)] for a,b in zip(path,path[1:])]
            reads = [rates.get(("measure" if i in (0,5) else "measure_2", (q,))) for i,q in enumerate(path)]
            if None not in reads:
                yield sum(reads) + sum(gates), path, reads, gates

    ranked = sorted(row for q in list(adj) for row in candidates([q]))
    best, path, reads, gates = ranked[0]
    original = next((row[0] for row in ranked if row[1] == ORIGINAL), None)
    return {"chain": path, "score": best, "readouts": reads, "cz_errors": gates,
            "candidate_count": len(ranked), "original_score": original}


def prepare(backend, layout):
    fast = all(backend.target.instruction_supported("measure_2", (q,)) for q in layout[1:5])
    if not fast:
        raise ValueError("The replication needs the same mid-circuit measurement as Fez")
    compiler = generate_preset_pass_manager(backend=backend, initial_layout=layout,
                                             optimization_level=0, seed_transpiler=SEED)
    compiled = compiler.run([circuit(s, fast) for s in SETTINGS], num_processes=1)
    for qc in compiled:
        backend.check_faulty(qc)
        measurements, conditionals, edges = {}, [], []
        for inst in qc.data:
            gate = inst.operation
            qubits = [qc.find_bit(q).index for q in inst.qubits]
            if gate.name != "barrier" and set(qubits) - set(layout):
                raise ValueError("Unexpected physical qubit")
            if gate.name in ("measure", "measure_2"):
                measurements[qc.find_bit(inst.clbits[0]).index] = qubits[0]
            if gate.name == "cz":
                edges.append(sorted(qubits))
            if gate.name == "if_else":
                bit, expected = gate.condition
                flag = qc.find_bit(bit).index
                if flag not in measurements or expected != 1:
                    raise ValueError("Unexpected feed-forward target or flag")
                conditionals.append((flag, qubits[0]))
        if (measurements != dict(enumerate(layout)) or sorted(conditionals) != [(1, layout[0]), (2, layout[0]), (3, layout[-1]), (4, layout[-1])]
                or sorted(edges) != sorted(sorted(edge) for edge in zip(layout, layout[1:]))):
            raise ValueError("Unexpected physical layout, gates, or measurement mapping")
    return compiled


def hardware():
    if json.loads(LOCAL.read_text())["correct"] != SHOTS * len(SETTINGS):
        raise RuntimeError("Run the ideal simulation first")
    if not sys.stdin.isatty():
        raise RuntimeError("Use an interactive terminal for private key entry")
    print("IBM Fez singlet teleportation | calibration-selected chain | 3 circuits, 256 shots each")
    key = getpass.getpass("IBM Cloud API key (hidden): ").strip()
    if not key:
        return
    service = QiskitRuntimeService(channel="ibm_quantum_platform", token=key,
                                   plans_preference=["open"], region="us-east")
    if RESULT.exists():
        record = json.loads(RESULT.read_text())
        if record["stage"] == "done":
            return
        if "job_id" in record:
            job = service.job(record["job_id"])
        else:
            matches = service.jobs(job_tags=[TAG], backend_name="ibm_fez", limit=2)
            if len(matches) != 1:
                raise RuntimeError("Reconcile prior submission before retry")
            job = matches[0]
    else:
        backend = service.backend("ibm_fez", use_fractional_gates=False)
        status = backend.status()
        if backend.is_mock or backend.name != "ibm_fez" or not status.operational:
            raise RuntimeError("Fez unavailable")
        props = backend.properties(refresh=True)
        selection = select_chain(props.to_dict(), props.faulty_qubits(), [g.to_dict() for g in props.faulty_gates()])
        layout = selection["chain"]
        compiled = prepare(backend, layout)
        options = {"environment": {"job_tags": [TAG]},
                   "twirling": {"enable_gates": False, "enable_measure": False},
                   "dynamical_decoupling": {"enable": False}}
        sampler = SamplerV2(mode=backend, options=options)
        record = {"backend": backend.name, "layout": layout, "setting_order": SETTINGS,
                  "shots_per_setting": SHOTS, "job_tag": TAG, "sampler_options": options,
                  "versions": {p: version(p) for p in ("qiskit", "qiskit-ibm-runtime")},
                  "created_utc": datetime.now(timezone.utc).isoformat(),
                  "calibration_updated": props.last_update_date if props else None,
                  "status_at_submission": status.to_dict(), "stage": "submitting",
                  "compiled_circuits": {s: str(qc.draw("text", idle_wires=False, fold=-1))
                                        for s, qc in zip(SETTINGS, compiled)}}
        record["selection"] = selection
        record["readout_at_submission"] = {
            str(q): backend.target["measure" if i in (0, 5) else "measure_2"][(q,)].error
            for i, q in enumerate(layout)
        }
        with RESULT.open("x", encoding="utf-8") as stream:
            json.dump(record, stream, indent=2, default=str)
        job = sampler.run(compiled, shots=SHOTS)
    record.update(job_id=job.job_id(), stage="submitted")
    save(RESULT, record)
    results = job.result()
    record.update(score([pub.data.c.get_counts() for pub in results]), stage="measured")
    save(RESULT, record)
    for _ in range(180):
        metrics = job.metrics()
        usage = metrics.get("usage", {})
        if usage.get("status", "pending") != "pending" and usage.get("qpu_charge_time_seconds") is not None:
            break
        time.sleep(5)
    record.update(stage="done", metrics=metrics)
    save(RESULT, record)
    print(record["expected_parity_counts"])


if __name__ == "__main__":
    if sys.argv[1:] == ["simulate"]:
        simulate()
    elif sys.argv[1:] == ["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            trace = traceback.extract_tb(exc.__traceback__)
            save(ROOT.parent / "work" / "fez-selected-singlet-error.json",
                 {"type": type(exc).__name__,
                  "frames": [[Path(f.filename).name, f.lineno, f.name] for f in trace]})
            print(f"Hardware step stopped ({type(exc).__name__}).")
        input("Press Enter to close.")
    else:
        raise SystemExit("Use simulate or hardware.")
