"""Run the local superdense coding check, then one IBM Fez job; reruns resume the saved 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

import numpy as np
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2


ROOT = Path(__file__).resolve().parent
RESULT = ROOT / "Fez-superdense-results.json"
LOCAL = ROOT / "Superdense-simulator.json"
SHOTS = 256
PAIR = [22, 23]
MESSAGES = ["00", "01", "10", "11"]
SEED = 221123
TAG = "fez-superdense-22-23-20261119-first"


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 circuits():
    settings = []
    for message in MESSAGES:
        qc = QuantumCircuit(2, 2, name="send_" + message)
        qc.h(0)
        qc.cx(0, 1)
        qc.barrier(label="shared_pair")
        # Qiskit prints c1 c0. The X encodes c1 (parity), the Z encodes c0 (phase).
        if message[0] == "1":
            qc.x(0)
        if message[1] == "1":
            qc.z(0)
        qc.barrier(label="handoff")
        qc.cx(0, 1)
        qc.h(0)
        qc.measure([0, 1], [0, 1])
        settings.append(qc)
    return settings


def counts(results):
    if len(results) != len(MESSAGES):
        raise ValueError("Missing message result")
    output = {}
    for message, pub in zip(MESSAGES, results):
        raw = pub.data.c.get_counts()
        if sum(raw.values()) != SHOTS or raw.keys() - {"00", "01", "10", "11"}:
            raise ValueError("Unexpected shots or bit strings")
        output[message] = {bits: raw.get(bits, 0) for bits in ("00", "01", "10", "11")}
    return output


def simulate():
    sampler = StatevectorSampler(seed=np.random.default_rng(SEED))
    data = counts(sampler.run(circuits(), shots=SHOTS).result())
    if any(data[bits][bits] != SHOTS for bits in MESSAGES):
        raise ValueError("Ideal superdense decoding failed")
    save(LOCAL, {"simulator": "Qiskit StatevectorSampler", "qiskit": version("qiskit"),
                 "seed": SEED, "shots_per_message": SHOTS, "counts": data})
    print(data)


def prepare(backend):
    compiler = generate_preset_pass_manager(backend=backend, initial_layout=PAIR,
                                             optimization_level=0, seed_transpiler=SEED)
    compiled = compiler.run(circuits(), num_processes=1)
    instructions = {}
    for message, qc in zip(MESSAGES, compiled):
        backend.check_faulty(qc)
        ops = [{"gate": inst.operation.name,
                "qubits": [qc.find_bit(q).index for q in inst.qubits],
                "clbits": [qc.find_bit(c).index for c in inst.clbits],
                "label": inst.operation.label,
                "params": [float(v) for v in inst.operation.params]} for inst in qc.data]
        measured = {op["clbits"][0]: op["qubits"][0] for op in ops if op["gate"] == "measure"}
        active = {q for op in ops if op["gate"] != "barrier" for q in op["qubits"]}
        if active != set(PAIR) or measured != dict(enumerate(PAIR)):
            raise ValueError("Compiled circuit changed the physical pair")
        shared = next(i for i, op in enumerate(ops) if op["label"] == "shared_pair")
        handoff = next(i for i, op in enumerate(ops) if op["label"] == "handoff")
        if handoff <= shared or any(op["qubits"] != PAIR[:1] for op in ops[shared+1:handoff]):
            raise ValueError("Compiled encoder crossed the handoff or used Bob's qubit")
        for block in (ops[:shared], ops[handoff+1:]):
            if not any(op["gate"] == "cz" and set(op["qubits"]) == set(PAIR) for op in block):
                raise ValueError("Missing entangling gate in preparation or decoding")
        instructions[message] = ops
    return compiled, instructions


def hardware():
    if not LOCAL.exists() or any(json.loads(LOCAL.read_text())['counts'][m][m] != SHOTS for m in MESSAGES):
        raise RuntimeError("Run the simulator first")
    if not sys.stdin.isatty():
        raise RuntimeError("Open the hardware step in an interactive console")
    print("IBM Quantum | Fez qubits 22 and 23 | 256 shots per message, four messages")
    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")
    backend = service.backend("ibm_fez")
    if RESULT.exists():
        record = json.loads(RESULT.read_text(encoding="utf-8"))
        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("Prior submission needs reconciliation")
            job = matches[0]
    else:
        status = backend.status()
        if backend.name != "ibm_fez" or backend.is_mock or not status.operational:
            raise RuntimeError("Fez is unavailable")
        props = backend.properties(refresh=True)
        compiled, instructions = prepare(backend)
        record = {"backend": backend.name, "physical_qubits": PAIR,
                  "shots_per_message": SHOTS, "message_order": MESSAGES,
                  "created_utc": datetime.now(timezone.utc).isoformat(),
                  "versions": {p: version(p) for p in ("qiskit", "qiskit-ibm-runtime")},
                  "calibration_updated": props.last_update_date if props else None,
                  "status_at_submission": status.to_dict(), "compiled_instructions": instructions,
                  "job_tag": TAG, "stage": "submitting"}
        sampler = SamplerV2(mode=backend, options={"environment": {"job_tags": [TAG]},
                            "twirling": {"enable_gates": False, "enable_measure": False},
                            "dynamical_decoupling": {"enable": False}})
        # Exclusive reservation prevents simultaneous launches from submitting twice.
        with RESULT.open("x", encoding="utf-8") as out:
            json.dump(record, out, indent=2, default=str)
        job = sampler.run(compiled, shots=SHOTS)
    record.update(job_id=job.job_id(), stage="submitted")
    save(RESULT, record)
    print(f"IBM job {job.job_id()}", flush=True)
    data = counts(job.result())
    record.update(counts=data, correct=sum(data[m][m] for m in MESSAGES), total=SHOTS * len(MESSAGES), 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(metrics=metrics, stage="done")
    save(RESULT, record)
    print(record["counts"], flush=True)


if __name__ == "__main__":
    if sys.argv[1:] == ["simulate"]:
        simulate()
    elif sys.argv[1:] == ["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            # Keep credential-bearing request bodies and headers out of local logs.
            trace = traceback.extract_tb(exc.__traceback__)
            issue = {"type": type(exc).__name__, "frames": [[Path(f.filename).name, f.lineno, f.name] for f in trace]}
            save(ROOT.parent / "work" / "superdense-error.json", issue)
            print(f"Hardware step stopped ({type(exc).__name__}).")
        input("Press Enter to close.")
    else:
        raise SystemExit("Use simulate or hardware.")
