# Données de la figure « Simon pas à pas » : jamais affiché comme extrait.
# La même exécution que 02-one-run.py (mêmes seeds), avec l'état à chaque pas.
import json

import numpy as np

from common import before_last_h, rounded, simon_function
from qsim import H, apply_single, measure_qubit, zero_state

n, secret = 3, 0b110
f = simon_function(secret, n, np.random.default_rng(42))
rng = np.random.default_rng(3)
labels = [format(x, "03b") for x in range(2**n)]

# Pas 1 : H sur l'entrée (le registre de sortie est encore |000⟩)
state = zero_state(2 * n)
for q in range(n):
    state = apply_single(state, H, q)
uniform = [float(rounded(state[x << n])) for x in range(2**n)]

# Pas 2 : un appel à l'oracle, chaque |x⟩ est lié à |f(x)⟩
state = before_last_h(f, n)
paired = [float(rounded(state[(x << n) | f[x]])) for x in range(2**n)]

# Pas 3 : lecture du registre de sortie
read = ""
for q in range(n, 2 * n):
    bit, state = measure_qubit(state, q, rng)
    read += str(bit)
out = int(read, 2)
rest = [float(rounded(state[(x << n) | out])) for x in range(2**n)]

# Pas 4 : H sur l'entrée, probabilités des résultats z
for q in range(n):
    state = apply_single(state, H, q)
probs = (np.abs(state) ** 2).reshape(2**n, 2**n).sum(axis=1)
print(json.dumps({
    "secret": format(secret, "03b"),
    "labels": labels,
    "f": [format(f[x], "03b") for x in range(2**n)],
    "uniform": uniform,
    "paired": paired,
    "read": read,
    "rest": rest,
    "z_probabilities": [float(p) for p in rounded(probs)],
}))
