"""Tests de l'étape 2 du mini-simulateur (atelier 4.8) : les portes à un qubit.

À enregistrer à côté du dossier qsim/, puis à lancer avec : python -m pytest -q
"""

import numpy as np
import pytest

from qsim.etape2_portes import (
    H, I, S, T, X, Y, Z,
    apply, apply_all, is_unitary, make_state, probabilities, rx, ry, rz, sample,
)

R = 1 / np.sqrt(2)


# --- L'étape 1 doit accepter des amplitudes complexes ---

def test_step1_accepts_complex_amplitudes():
    state = make_state(0.6, 0.8j)   # |0,6|² + |0,8i|² = 1
    assert np.allclose(probabilities(state), [0.36, 0.64])


# --- Les matrices des portes ---

def test_gates_have_the_right_matrices():
    assert np.allclose(X, [[0, 1], [1, 0]])
    assert np.allclose(Y, [[0, -1j], [1j, 0]])
    assert np.allclose(Z, [[1, 0], [0, -1]])
    assert np.allclose(H, [[R, R], [R, -R]])
    assert np.allclose(S, [[1, 0], [0, 1j]])
    assert np.allclose(T, [[1, 0], [0, np.exp(1j * np.pi / 4)]])


def test_phase_gates_compose():
    assert np.allclose(T @ T, S)
    assert np.allclose(S @ S, Z)


# --- is_unitary ---

def test_standard_gates_are_unitary():
    for gate in (I, X, Y, Z, H, S, T):
        assert is_unitary(gate)


def test_non_unitary_matrices_are_rejected():
    assert not is_unitary(np.array([[1, 1], [0, 1]]))
    assert not is_unitary(np.array([[1, 0], [0, 2]]))
    assert not is_unitary(np.ones((2, 3)))   # pas carrée


def test_is_unitary_returns_a_single_bool():
    # un seul booléen, pas un tableau de booléens
    assert isinstance(is_unitary(H), (bool, np.bool_))


# --- apply ---

def test_apply_x_flips():
    assert np.allclose(apply(make_state(1, 0), X), [0, 1])
    assert np.allclose(apply(make_state(0, 1), X), [1, 0])


def test_apply_h_gives_plus_and_minus():
    assert np.allclose(apply(make_state(1, 0), H), [R, R])
    assert np.allclose(apply(make_state(0, 1), H), [R, -R])


def test_apply_y_and_phases():
    assert np.allclose(apply(make_state(1, 0), Y), [0, 1j])
    assert np.allclose(apply(make_state(0, 1), Z), [0, -1])
    assert np.allclose(apply(make_state(0, 1), S), [0, 1j])


def test_apply_rejects_a_non_unitary_matrix():
    with pytest.raises(ValueError):
        apply(make_state(1, 0), np.array([[1, 1], [0, 1]]))


def test_apply_does_not_modify_its_input():
    state = make_state(0.6, 0.8)
    apply(state, X)
    assert np.allclose(state, [0.6, 0.8])


def test_apply_keeps_probabilities_summing_to_one():
    state = make_state(0.6, 0.8j)
    for gate in (X, Y, Z, H, S, T, rx(0.3), ry(1.2), rz(2.5)):
        assert np.isclose(probabilities(apply(state, gate)).sum(), 1)


# --- apply_all ---

def test_apply_all_follows_the_circuit_order():
    # « X puis H » depuis |0⟩ donne |−⟩ ; « H puis X » donne |+⟩
    assert np.allclose(apply_all(make_state(1, 0), [X, H]), [R, -R])
    assert np.allclose(apply_all(make_state(1, 0), [H, X]), [R, R])


def test_apply_all_with_no_gate_changes_nothing():
    state = make_state(0.6, 0.8)
    assert np.allclose(apply_all(state, []), state)


def test_h_twice_is_identity():
    state = make_state(0.6, 0.8j)
    assert np.allclose(apply_all(state, [H, H]), state)


def test_hzh_reveals_the_phase():
    # le circuit « H, Z, H » depuis |0⟩ donne toujours 1 (leçon 4.4)
    state = apply_all(make_state(1, 0), [H, Z, H])
    assert sample(state, 100, seed=1) == {"1": 100}


# --- Les rotations ---

def test_rotations_are_unitary():
    for theta in (0.0, 0.4, np.pi / 3, 2.0):
        for gate in (rx(theta), ry(theta), rz(theta)):
            assert is_unitary(gate)


def test_ry_sets_the_probability():
    state = apply(make_state(1, 0), ry(np.pi / 3))
    assert np.allclose(probabilities(state), [0.75, 0.25])


def test_rotations_match_the_gates_of_4_4():
    assert np.allclose(rx(np.pi), -1j * X)
    assert np.allclose(ry(np.pi), -1j * Y)
    assert np.allclose(rz(np.pi), -1j * Z)
    assert np.allclose(rz(np.pi / 2), np.exp(-1j * np.pi / 4) * S)


def test_full_turn_is_minus_identity():
    assert np.allclose(rx(2 * np.pi), -np.eye(2))
    assert np.allclose(rz(4 * np.pi), np.eye(2))
