import numpy as np
from common import qft_matrix

from qsim import H, apply_cnot, apply_single, num_qubits

gate_count = {"H": 0, "phase contrôlée": 0, "échange": 0}


def apply_cphase(state, control, target, phi):
    """Phase contrôlée : multiplie par exp(iφ) les amplitudes où les deux qubits valent 1."""
    gate_count["phase contrôlée"] += 1
    n = num_qubits(state)
    result = state.astype(complex)
    for index in range(len(state)):
        bits = format(index, f"0{n}b")
        if bits[control] == "1" and bits[target] == "1":
            result[index] *= np.exp(1j * phi)
    return result


def apply_swap(state, a, b):
    """Échange deux qubits avec trois CNOT."""
    gate_count["échange"] += 1
    state = apply_cnot(state, a, b)
    state = apply_cnot(state, b, a)
    return apply_cnot(state, a, b)


def qft_circuit(state):
    n = num_qubits(state)
    for q in range(n):
        gate_count["H"] += 1
        state = apply_single(state, H, q)
        # phase 2π/2**k, contrôlée par chacun des qubits suivants
        for m in range(q + 1, n):
            state = apply_cphase(state, m, q, 2 * np.pi / 2 ** (m - q + 1))
    # le circuit sort les qubits dans l'ordre inverse : on les remet en place
    for q in range(n // 2):
        state = apply_swap(state, q, n - 1 - q)
    return state


# On applique le circuit à chaque état de base : les colonnes forment sa matrice
n = 4
columns = [qft_circuit(np.eye(2**n)[:, i]) for i in range(2**n)]
print("circuit = matrice QFT :", np.allclose(np.column_stack(columns), qft_matrix(n)))

# Portes pour une seule passe sur 4 qubits
gate_count = dict.fromkeys(gate_count, 0)
qft_circuit(np.eye(2**n)[:, 0])
print("portes pour n = 4 :", gate_count)
