# timeout: 180
# Corriger les erreurs de lecture : étalonner, puis inverser
import numpy as np
from qiskit import QuantumCircuit
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_aer.noise import NoiseModel
from qiskit_aer.primitives import SamplerV2 as AerSampler
from qiskit_ibm_runtime.fake_provider import FakeFez

from common import bar_chart, clip_and_normalize

SHOTS = 10_000
LABELS = ["00", "01", "10", "11"]  # ordre de Qiskit : qubit 0 à droite

# 1. Circuits d'étalonnage : on prépare chacun des quatre états de base, puis on lit
calibration = []
for label in LABELS:
    qc = QuantumCircuit(2)
    for qubit, bit in enumerate(reversed(label)):
        if bit == "1":
            qc.x(qubit)
    qc.measure_all()
    calibration.append(qc)

# 2. Le circuit à corriger : l'état de Bell
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()

fake = FakeFez()
pm = generate_preset_pass_manager(optimization_level=1, backend=fake, seed_transpiler=7, initial_layout=[0, 1])
sampler = AerSampler(seed=42, options={"backend_options": {"noise_model": NoiseModel.from_backend(fake)}})
results = sampler.run(pm.run(calibration + [bell]), shots=SHOTS).result()


def distribution(result):
    counts = result.data.meas.get_counts()
    return np.array([counts.get(label, 0) / SHOTS for label in LABELS])


# Matrice d'étalonnage : colonne j = ce qu'on lit quand on a préparé l'état j
assignment = np.column_stack([distribution(res) for res in results[:4]])
print("Matrice d'étalonnage (colonne = état préparé, ligne = état lu) :")
print("       " + "      ".join(LABELS))
for label, row in zip(LABELS, assignment):
    print(f"  {label}  " + "  ".join(f"{round(float(v), 4) + 0.0:.4f}" for v in row))

raw = distribution(results[4])
corrected = clip_and_normalize(np.linalg.solve(assignment, raw))
print("\nBell, brut :")
print(bar_chart(dict(zip(LABELS, raw))))
print("Bell, lecture corrigée :")
print(bar_chart(dict(zip(LABELS, corrected))))
print(f"\nP(01) + P(10) : brut {raw[1] + raw[2]:.4f}, corrigé {corrected[1] + corrected[2]:.4f}")

# Ce que la lecture seule ferait de l'état de Bell parfait : M fois (0,5 ; 0 ; 0 ; 0,5)
ideal = np.array([0.5, 0, 0, 0.5])
print("M @ Bell parfait :", np.round(assignment @ ideal, 4))
