"""IBM CHSH angle sweep, four raw-count bases shared by disjoint Bell pairs."""
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.circuit import Parameter
from qiskit.quantum_info import Statevector
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
from qiskit_ibm_runtime.fake_provider import FakeFez

ROOT = Path(__file__).resolve().parent
HW = ROOT / "CHSH-hardware.json"
SIM = ROOT / "CHSH-simulator.json"
RAW = ROOT / "CHSH-packed-shots.npz"
TAG = "ibm-chsh-sweep-20261119-first"
BASES = ("ZZ", "ZX", "XZ", "XX")  # Qiskit labels: Bob then Alice
SIGNS = np.array([[1, -1, 1, 1], [1, 1, -1, 1]])
ANGLES = np.linspace(0, 2*np.pi, 21)
PRIMARY = 2  # 36 degrees; positive S2 is the prespecified witness
SHOTS = 256
SEED = 1936


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(n):
    theta = Parameter("theta")
    result = []
    for bob, alice in BASES:
        qc = QuantumCircuit(2*n, 2*n, name="basis_" + bob + alice)
        for a in range(0, 2*n, 2):
            qc.h(a)
            qc.cx(a, a+1)
        qc.barrier()
        for a in range(0, 2*n, 2):
            qc.ry(theta, a)
            if alice == "X":
                qc.h(a)
            if bob == "X":
                qc.h(a+1)
        qc.measure(range(2*n), range(2*n))
        result.append(qc)
    return result


def ideal_curves():
    return np.array([2*(np.cos(ANGLES)-np.sin(ANGLES)), 2*(np.cos(ANGLES)+np.sin(ANGLES))])


def simulate():
    qcs = circuits(1)
    exact = []
    for qc in qcs:
        qc = qc.remove_final_measurements(inplace=False)
        probs = [Statevector.from_instruction(qc.assign_parameters([t])).probabilities() for t in ANGLES]
        exact.append(np.asarray(probs) @ [1, -1, -1, 1])
    assert np.allclose(SIGNS @ exact, ideal_curves())
    fake = FakeFez()
    sim = AerSimulator.from_backend(fake, method="density_matrix")
    pair = [22, 23]
    pm = generate_preset_pass_manager(backend=fake, initial_layout=pair, optimization_level=1,
                                      seed_transpiler=SEED)
    compiled = pm.run(qcs, num_processes=1)
    sweep = [qc.assign_parameters([t]) for qc in compiled for t in ANGLES]
    run = sim.run(sweep, shots=SHOTS, seed_simulator=SEED).result()
    rows = run.get_counts()
    assert len(rows) == 4*len(ANGLES) and all(sum(row.values()) == SHOTS for row in rows)
    ev = np.array([2*(row.get("00",0)+row.get("11",0))/SHOTS-1 for row in rows]).reshape(4,-1)
    record = {"model":"Aer density matrix, packaged FakeFez calibration snapshot", "pair":pair,
              "seed":SEED, "angles_deg":np.degrees(ANGLES).round(6).tolist(), "bases":BASES,
              "shots_per_setting":SHOTS, "counts":rows, "ideal_S":ideal_curves().tolist(),
              "noisy_S":(SIGNS @ ev).tolist()}
    save(SIM, record)
    print("At 36 degrees: ideal S2",ideal_curves()[1,PRIMARY],"noisy S2",record["noisy_S"][1][PRIMARY])


def compile_pairs(backend):
    p = backend.properties(refresh=True)
    used = set(p.faulty_qubits())
    faulty = {tuple(sorted(g.qubits)) for g in p.faulty_gates() if len(g.qubits)==2}
    edges = sorted({tuple(sorted(edge)) for edge in backend.coupling_map.get_edges()})
    pairs = []
    for a,b in edges:
        if a not in used and b not in used and (a,b) not in faulty:
            pairs.append((a,b))
            used.update((a,b))
    if not pairs:
        raise ValueError("No healthy Bell pairs")
    layout = [i for pair in pairs for i in pair]
    pm = generate_preset_pass_manager(backend=backend, initial_layout=layout, optimization_level=1,
                                      seed_transpiler=SEED)
    compiled = pm.run(circuits(len(pairs)), num_processes=1)
    for qc in compiled:
        backend.check_faulty(qc)
        measured = {qc.find_bit(op.clbits[0]).index:qc.find_bit(op.qubits[0]).index
                    for op in qc.data if op.operation.name=="measure"}
        twoq = [tuple(sorted(qc.find_bit(q).index for q in op.qubits)) for op in qc.data
                if len(op.qubits)==2 and op.operation.name!="barrier"]
        if measured != dict(enumerate(layout)) or sorted(twoq)!=sorted(pairs) or qc.num_parameters!=1:
            raise ValueError("Compiled measurements or pairs changed")
    return pairs, compiled, str(p.last_update_date)


def analyze(packed, pairs):
    n = len(pairs)
    correlations, mean_variances = [], []
    for basis in BASES:
        raw = packed[basis]
        if raw.shape != (len(ANGLES), SHOTS, (2*n+7)//8):
            raise ValueError(f"Unexpected shot array for {basis}: {raw.shape}")
        bits = np.unpackbits(raw, axis=-1)[..., ::-1][..., :2*n]
        parity = (bits[..., ::2] ^ bits[..., 1::2]).astype(float)
        observations = 1 - 2*parity
        correlations.append(observations.mean(axis=1))
        # First average simultaneous pairs within a shot, retaining their covariance.
        mean_variances.append(observations.mean(axis=2).var(axis=1,ddof=1)/SHOTS)
    witnesses = np.einsum("wb,btp->wtp",SIGNS,np.asarray(correlations))
    mean = witnesses.mean(axis=2)
    se = np.sqrt(np.sum(mean_variances,axis=0))
    primary = witnesses[1,PRIMARY]
    # One-sided Hoeffding bound at prespecified angle, Bonferroni across pairs.
    threshold = 2 + np.sqrt(8*np.log(n/.05)/SHOTS)
    return {"correlator_order":BASES, "correlations_basis_angle_pair":np.array(correlations).tolist(),
            "S_witness_angle_pair":witnesses.tolist(), "mean_S":mean.tolist(),
            "mean_S_shot_se":se.tolist(), "primary_angle_deg":36, "primary_witness":"S2",
            "primary_mean":mean[1,PRIMARY], "primary_se":se[PRIMARY],
            "primary_pairs_above_2":int(sum(primary>2)),
            "primary_bonferroni_hoeffding_threshold":threshold,
            "primary_pairs_passing_adjusted_test":int(sum(primary>threshold)),
            "pairs_any_observed_crossing":int(np.sum(np.max(abs(witnesses),axis=(0,1))>2))}


def plot(record):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    deg = np.degrees(ANGLES)
    fig, ax = plt.subplots(figsize=(9,4.8), layout="constrained")
    ax.axhspan(-2, 2, color="#edf0f2", zorder=0)
    for y in (-2,2):
        ax.axhline(y,color="#58636d",lw=1)
    curves = np.array(record["analysis"]["mean_S"])
    errors = 1.96*np.array(record["analysis"]["mean_S_shot_se"])
    dense = np.linspace(0,2*np.pi,361)
    for i,(color,sgn) in enumerate([("#286589",-1),("#ad4936",1)]):
        ax.plot(np.degrees(dense),2*(np.cos(dense)+sgn*np.sin(dense)),ls="--",c=color,alpha=.55)
        ax.errorbar(deg,curves[i],yerr=errors,c=color,fmt="o-",ms=3.5,lw=1.6,
                    label=f"S{i+1} hardware")
    ax.set(xlim=(-4,364),ylim=(-3.2,3.2),xticks=np.arange(0,361,45),
           xlabel="Rotation of the first qubit (degrees)",ylabel="Mean CHSH value",
           title=f"{record['backend']}  |  {len(record['pairs'])} parallel Bell pairs")
    ax.plot([],[],ls="--",c="#58636d",label="Ideal")
    ax.fill_between([],[],[],color="#edf0f2",label="Local classical range")
    ax.legend(ncol=4,loc="upper center",bbox_to_anchor=(.5,-.15),frameon=False)
    fig.savefig(ROOT/"CHSH-angle-sweep.png",dpi=170)
    plt.close(fig)


def hardware():
    if not SIM.exists() or not sys.stdin.isatty():
        raise RuntimeError("Run the simulation and use an interactive console")
    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 HW.exists():
        record = json.loads(HW.read_text())
        if record["stage"]=="done":
            plot(record)
            return
        if "job_id" in record:
            job = service.job(record["job_id"])
        else:
            matches = service.jobs(job_tags=[TAG],limit=2)
            if len(matches)!=1:
                raise RuntimeError("Reconcile prior submission")
            job = matches[0]
    else:
        devices = {b.name:b for b in service.backends(simulator=False,min_num_qubits=2) if not b.is_mock}
        prepared = {}
        while True:
            queues = {k:b.status().to_dict() for k,b in devices.items()}
            timestamp = datetime.now(timezone.utc).isoformat()
            active = [k for k,s in queues.items() if s["operational"] and s["status_msg"].lower()=="active"]
            name = min(active,key=lambda k:(queues[k]["pending_jobs"],k))
            if name in prepared:
                break
            prepared[name] = compile_pairs(devices[name])
        pairs, isa, calibration = prepared[name]
        record = {"stage":"submitting","backend":name,"queues":queues,"queue_snapshot_utc":timestamp,
                  "pairs":pairs,"calibration_updated":calibration,"bases":BASES,
                  "shots_per_basis_angle":SHOTS,"angles_deg":np.degrees(ANGLES).round(6).tolist(),
                  "primary_test":"positive S2 at 36 degrees","tag":TAG,
                  "versions":{p:version(p) for p in ("qiskit","qiskit-ibm-runtime","qiskit-aer")}}
        sampler = SamplerV2(mode=devices[name],options={"environment":{"job_tags":[TAG]},
                            "twirling":{"enable_gates":False,"enable_measure":False},
                            "dynamical_decoupling":{"enable":False}})
        with HW.open("x", encoding="utf8") as out:
            json.dump(record,out,indent=2)
        job = sampler.run([(qc,ANGLES[:,None]) for qc in isa],shots=SHOTS)
    record.update(stage="submitted",job_id=job.job_id())
    save(HW,record)
    while True:
        status = str(job.status())
        if status!=record.get("ibm_status"):
            record["ibm_status"]=status
            save(HW,record)
        if status in ("DONE","ERROR","CANCELLED"):
            break
        time.sleep(10)
    pubs = job.result()
    assert len(pubs)==4
    packed = {basis:pub.data.c.array for basis,pub in zip(BASES,pubs)}
    np.savez_compressed(RAW,**packed)
    record.update(stage="measured",analysis=analyze(packed,record["pairs"]))
    save(HW,record)
    for _ in range(180):
        metrics = job.metrics()
        if metrics.get("usage",{}).get("status")=="complete":
            break
        time.sleep(5)
    record.update(stage="done",metrics=metrics)
    save(HW,record)
    plot(record)
    print("CHSH S2 at 36 degrees:",record["analysis"]["primary_mean"])


if __name__=="__main__":
    if sys.argv[1:]==["simulate"]:
        simulate()
    elif sys.argv[1:]==["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            save(ROOT.parent/"work"/"chsh-error.json",{"type":type(exc).__name__,
                 "frames":[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]})
            print(type(exc).__name__)
        input("Press Enter to close.")
