# timeout: 120
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import hellinger_fidelity
from qiskit_ibm_runtime.fake_provider import FakeFez

from common import IDEAL, SHOTS, ghz, noisy_sampler, transpile_for

N = 4
backend = FakeFez()
sampler = noisy_sampler(backend)
keys = [format(i, f"0{N}b") for i in range(2**N)]


def confusion_matrix(qubits):
    """Matrice d'étalonnage de la lecture, une matrice 2 × 2 par qubit (leçon 11.6)."""
    # Deux circuits d'étalonnage sur les mêmes qubits physiques : tout à 0, tout à 1
    all_zero = QuantumCircuit(N)
    all_zero.measure_all()
    all_one = QuantumCircuit(N)
    all_one.x(range(N))
    all_one.measure_all()
    calibration = [transpile_for(backend, qc, initial_layout=qubits) for qc in (all_zero, all_one)]
    result = sampler.run(calibration, shots=SHOTS).result()
    zeros, ones = (pub.data.meas.get_counts() for pub in result)
    matrix = np.array([[1.0]])
    for q in reversed(range(N)):  # Qiskit : le qubit 0 est le bit le plus à droite
        p1_given_0 = sum(v for k, v in zeros.items() if k[N - 1 - q] == "1") / SHOTS
        p0_given_1 = sum(v for k, v in ones.items() if k[N - 1 - q] == "0") / SHOTS
        single = np.array([[1 - p1_given_0, p0_given_1], [p1_given_0, 1 - p0_given_1]])
        matrix = np.kron(matrix, single)
    return matrix


for level in (1, 3):
    isa = transpile_for(backend, ghz(N), level=level)
    qubits = isa.layout.final_index_layout()
    counts = sampler.run([isa], shots=SHOTS).result()[0].data.meas.get_counts()
    measured = np.array([counts.get(k, 0) for k in keys]) / SHOTS
    # On inverse la lecture : on cherche la distribution qui, mal lue, donne ce qu'on a mesuré
    corrected = np.linalg.solve(confusion_matrix(qubits), measured)
    corrected = np.clip(corrected, 0, None)
    corrected /= corrected.sum()
    fixed = {k: float(p) for k, p in zip(keys, corrected) if p > 0}
    before = hellinger_fidelity(counts, IDEAL)
    after = hellinger_fidelity(fixed, IDEAL)
    print(f"Niveau {level}, qubits {qubits} : fidélité {before:.3f} avant, {after:.3f} après correction")
