"""Run the local Bell 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-Bell-results.json"
LOCAL = ROOT / "Bell-simulator.json"
SHOTS = 256
PAIR = [22, 23]
BASES = ["ZZ", "XX"]
SEED = 221123
TAG = "fez-bell-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 basis in BASES:
        qc = QuantumCircuit(2, 2, name=basis)
        qc.h(0)
        qc.cx(0, 1)
        qc.barrier()
        if basis == "XX":
            qc.h([0, 1])
        qc.measure([0, 1], [0, 1])
        settings.append(qc)
    return settings


def counts(results):
    if len(results) != len(BASES):
        raise ValueError("Missing measurement setting")
    output = {}
    for basis, pub in zip(BASES, 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[basis] = {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(row["01"] or row["10"] or not (row["00"] and row["11"]) for row in data.values()):
        raise ValueError("Ideal Bell-pair simulation failed")
    save(LOCAL, {"simulator": "Qiskit StatevectorSampler", "qiskit": version("qiskit"),
                 "seed": SEED, "shots_per_setting": SHOTS, "counts": data})
    print(data)


def prepare(backend):
    compiler = generate_preset_pass_manager(backend=backend, initial_layout=PAIR,
                                             optimization_level=1, seed_transpiler=SEED)
    compiled = compiler.run(circuits(), num_processes=1)
    instructions = {}
    for basis, qc in zip(BASES, 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],
                "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")
        instructions[basis] = ops
    return compiled, instructions


def hardware():
    if not LOCAL.exists():
        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 in Z and 256 in X")
    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 "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_setting": SHOTS, "basis_order": BASES,
                  "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)
    record.update(counts=counts(job.result()), 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" / "bell-error.json", issue)
            print(f"Hardware step stopped ({type(exc).__name__}).")
        input("Press Enter to close.")
    else:
        raise SystemExit("Use simulate or hardware.")
