"""Tests de l'atelier 6.4 : votre étape 3 du mini-simulateur, plusieurs qubits.

Rangez ce fichier à côté de votre dossier qsim/ (qui contient __init__.py, vide,
etape1_un_qubit.py, etape2_portes.py et etape3_plusieurs_qubits.py), puis lancez : python -m pytest -q
"""

import numpy as np
import pytest

from qsim.etape3_plusieurs_qubits import (
    H,
    ONE,
    S,
    X,
    ZERO,
    apply,
    apply_cnot,
    apply_single,
    kron,
    make_state,
    measure_qubit,
    num_qubits,
    sample,
    zero_state,
)


def basis(bits):
    """L'état de base |bits⟩, par exemple basis("10") ; le qubit 0 est le bit de gauche."""
    state = np.zeros(2 ** len(bits))
    state[int(bits, 2)] = 1
    return state


# --- L'état de n qubits ---------------------------------------------------------


def test_zero_state():
    assert np.allclose(zero_state(1), [1, 0])
    assert np.allclose(zero_state(3), basis("000"))


def test_num_qubits():
    assert num_qubits(np.zeros(4)) == 2
    assert num_qubits(np.zeros(8)) == 3
    with pytest.raises(ValueError):
        num_qubits(np.zeros(6))


def test_kron_puts_qubit_0_on_the_left():
    assert np.allclose(kron(ONE, ZERO), basis("10"))
    assert np.allclose(kron(ZERO, ONE, ONE), basis("011"))


# --- Une porte à un qubit dans un registre ----------------------------------------


def test_apply_single_targets_the_right_qubit():
    assert np.allclose(apply_single(zero_state(2), X, 0), basis("10"))
    assert np.allclose(apply_single(zero_state(2), X, 1), basis("01"))
    assert np.allclose(apply_single(zero_state(3), X, 2), basis("001"))


def test_apply_single_leaves_other_qubits_alone():
    psi = make_state(0.6, 0.8)
    state = apply_single(kron(psi, ZERO), H, 1)
    assert np.allclose(state, kron(psi, apply(ZERO, H)))


def test_apply_single_rejects_bad_input():
    with pytest.raises(ValueError):
        apply_single(zero_state(2), X, 2)  # pas de qubit 2 dans un état de 2 qubits
    with pytest.raises(ValueError):
        apply_single(zero_state(2), np.array([[1, 1], [0, 1]]), 0)  # porte non unitaire


# --- Le CNOT ----------------------------------------------------------------------


def test_cnot_truth_table_control_0():
    for start, end in {"00": "00", "01": "01", "10": "11", "11": "10"}.items():
        assert np.allclose(apply_cnot(basis(start), 0, 1), basis(end))


def test_cnot_truth_table_control_1():
    for start, end in {"00": "00", "01": "11", "10": "10", "11": "01"}.items():
        assert np.allclose(apply_cnot(basis(start), 1, 0), basis(end))


def test_cnot_on_three_qubits_skips_the_middle_one():
    assert np.allclose(apply_cnot(basis("100"), 0, 2), basis("101"))
    assert np.allclose(apply_cnot(basis("110"), 0, 2), basis("111"))


def test_cnot_keeps_complex_amplitudes():
    state = kron(apply(apply(ZERO, H), S), ZERO)  # (|00⟩ + i|10⟩) / √2
    expected = np.array([1, 0, 0, 1j]) / np.sqrt(2)
    assert np.allclose(apply_cnot(state, 0, 1), expected)


def test_cnot_rejects_bad_qubits():
    with pytest.raises(ValueError):
        apply_cnot(zero_state(2), 1, 1)
    with pytest.raises(ValueError):
        apply_cnot(zero_state(2), 0, 2)


# --- L'état de Bell et les shots ------------------------------------------------


def bell():
    return apply_cnot(apply_single(zero_state(2), H, 0), 0, 1)


def test_bell_state():
    assert np.allclose(bell(), np.array([1, 0, 0, 1]) / np.sqrt(2))


def test_sample_works_for_n_qubits():
    counts = sample(bell(), 1000, seed=42)
    assert set(counts) == {"00", "11"}
    assert sum(counts.values()) == 1000
    assert sample(zero_state(3), 10, seed=0) == {"000": 10}


# --- La mesure d'un seul qubit ----------------------------------------------------


def test_measure_qubit_returns_outcome_and_full_state():
    rng = np.random.default_rng(42)
    outcome, after = measure_qubit(kron(ONE, ZERO), 0, rng)
    assert outcome == 1
    assert after.shape == (4,)
    assert np.allclose(np.abs(after) ** 2, [0, 0, 1, 0])


def test_measure_qubit_follows_the_probabilities():
    rng = np.random.default_rng(42)
    state = kron(make_state(0.6, 0.8), ZERO)  # P(qubit 0 = 1) = 0.64
    ones = sum(measure_qubit(state, 0, rng)[0] for _ in range(2000))
    assert abs(ones / 2000 - 0.64) < 0.04


def test_measure_qubit_renormalizes():
    rng = np.random.default_rng(42)
    state = apply_single(apply_single(zero_state(2), H, 0), H, 1)
    for _ in range(10):
        _, after = measure_qubit(state, 0, rng)
        assert np.isclose(np.sum(np.abs(after) ** 2), 1)


def test_measure_one_qubit_of_bell_fixes_the_other():
    rng = np.random.default_rng(42)
    for _ in range(20):
        first, after = measure_qubit(bell(), 0, rng)
        second, _ = measure_qubit(after, 1, rng)
        assert first == second
