import numpy as np

from qsim.etape2_portes import H, S, T


def key(gate):
    """Clé d'une porte « à une phase globale près » : on fixe la phase du premier coefficient non nul."""
    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)  # + 0.0 : pas de -0.0


def count_distinct(generators, max_length):
    """Nombre de portes distinctes obtenues en enchaînant au plus `max_length` générateurs."""
    seen = {key(np.eye(2))}
    frontier = [np.eye(2)]
    counts = []
    for _ in range(max_length):
        new = []
        for gate in frontier:
            for g in generators:
                product = g @ gate
                k = key(product)
                if k not in seen:
                    seen.add(k)
                    new.append(product)
        frontier = new
        counts.append(len(seen))
    return counts


for name, generators in (("H, S", [H, S]), ("H, T", [H, T])):
    counts = count_distinct(generators, 16)
    print(f"{name} : portes distinctes après 4, 8, 12, 16 portes ->", counts[3], counts[7], counts[11], counts[15])
