import numpy as np

from qsim.etape2_portes import H, T, X, I, ry, rz


def key(gate):
    """Clé d'une porte à une phase globale près (comme dans 02-finite-or-not.py)."""
    gate = np.asarray(gate, dtype=complex)
    first = gate.flat[np.flatnonzero(np.abs(gate) > 1e-9)[0]]
    canonical = np.round(gate / (first / abs(first)), 6)
    return tuple((float(z.real) + 0.0, float(z.imag) + 0.0) for z in canonical.flat)


def gap(u, v):
    """Écart entre deux portes : 0 si elles ne diffèrent que d'une phase globale, au plus 1."""
    overlap = abs(np.trace(u.conj().T @ v)) / 2
    return float(np.sqrt(max(0.0, 1 - overlap**2)))


print("écart(T, RZ(π/4)) =", round(gap(T, rz(np.pi / 4)), 3), "  (même porte, à une phase près)")
print("écart(I, X)       =", round(gap(I, X), 3))

target = ry(1.0)  # une rotation d'un radian autour de Y
seen = {key(np.eye(2))}
frontier = [np.eye(2, dtype=complex)]
best = gap(np.eye(2), target)

# Force brute : toutes les portes distinctes qu'on obtient avec au plus `length` portes H et T
for length in range(1, 31):
    new = []
    for gate in frontier:
        for g in (H, T):
            product = g @ gate
            k = key(product)
            if k not in seen:
                seen.add(k)
                new.append(product)
                best = min(best, gap(product, target))
    frontier = new
    if length in (5, 10, 20, 30):
        print(f"au plus {length:2d} portes : {len(seen):6d} portes candidates, meilleur écart = {best:.3f}")
