import numpy as np

from qsim.etape2_portes import H, apply
from qsim.etape1_un_qubit import ZERO

np.set_printoptions(precision=3, suppress=True)

# Exercice 3 : contrôles a, b en superposition, bit de travail w (qubit 2)
CCX = np.eye(8)
CCX[[6, 7]] = CCX[[7, 6]]
plus = apply(ZERO, H)
start = np.kron(np.kron(plus, plus), ZERO)
computed = CCX @ start  # w = a ET b


def controls_probabilities(state):
    # Probabilités de lire a, b (00, 01, 10, 11), quel que soit w
    return (np.abs(state) ** 2).reshape(4, 2).sum(axis=1)


# Option 1 : décalculer avec un second Toffoli
uncomputed = CCX @ computed
print("décalcul, w revient à |0⟩ :", np.allclose(uncomputed, start))
print("  P(ab) après décalcul :", controls_probabilities(uncomputed))

# Option 2 : lire w (supposons qu'on lise 0), puis le remettre à 0
keep = np.array([index % 2 == 0 for index in range(8)])  # composantes où w = 0
p_w0 = float(np.sum(np.abs(computed[keep]) ** 2))
measured = np.where(keep, computed, 0) / np.sqrt(p_w0)
print("lecture de w : P(w = 0) =", round(p_w0, 3))
print("  P(ab) si on a lu w = 0 :", controls_probabilities(measured))
