"""Code partagé de la leçon 4.6 : les rotations, les portes de 4.4 et le point de Bloch de la leçon 3.3."""

import numpy as np

I = np.eye(2)
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.array([[1, 0], [0, -1]])
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
S = np.array([[1, 0], [0, 1j]])
T = np.array([[1, 0], [0, np.exp(1j * np.pi / 4)]])


def rx(theta):
    """Rotation d'angle theta autour de l'axe x de la sphère de Bloch."""
    c, s = np.cos(theta / 2), np.sin(theta / 2)
    return np.array([[c, -1j * s], [-1j * s, c]])


def ry(theta):
    """Rotation d'angle theta autour de l'axe y (une matrice réelle)."""
    c, s = np.cos(theta / 2), np.sin(theta / 2)
    return np.array([[c, -s], [s, c]])


def rz(theta):
    """Rotation d'angle theta autour de l'axe z."""
    return np.array([[np.exp(-1j * theta / 2), 0], [0, np.exp(1j * theta / 2)]])


def bloch_angles(state):
    """Les angles de la leçon 3.3 : θ depuis le pôle nord (de 0 à π), φ autour de l'axe vertical (de 0 à 2π)."""
    a, b = state
    theta = 2 * np.arccos(min(abs(a), 1.0))
    phi = (np.angle(b) - np.angle(a)) % (2 * np.pi)
    return float(theta), float(phi)


def bloch_vector(state):
    """Les coordonnées (x, y, z) du point de Bloch, comme dans la leçon 3.3."""
    theta, phi = bloch_angles(state)
    return np.array([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)])


def point(state):
    """Le point de Bloch, arrondi et écrit (x, y, z)."""
    x, y, z = np.round(bloch_vector(state), 3) + 0.0
    return f"({x:g}, {y:g}, {z:g})"


def fmt(z):
    """Un nombre arrondi à 3 décimales, sans partie nulle ni « -0 » : 0.6, 0.8j, 0.6+0.8j."""
    z = complex(np.round(complex(z), 3))
    re, im = z.real + 0.0, z.imag + 0.0
    if im == 0:
        return f"{re:g}"
    if re == 0:
        return f"{im:g}j"
    return f"{re:g}{im:+g}j"


def show(array):
    """Un vecteur ou une matrice, écrit avec fmt."""
    array = np.asarray(array)
    if array.ndim == 1:
        return "[" + ", ".join(fmt(z) for z in array) + "]"
    return "[" + ", ".join(show(row) for row in array) + "]"
