"""
version = "0.2.2.dev0"
Particle simulation animation run through Matplotlib's FuncAnimation.

    mount(state)          -> allocate window + ONE artist
    present()             -> push `state` to the artist
    run(advance, frames)  -> own the clock; advance() then present() per frame

The simulation owns `state` and `advance`. The renderer owns the clock
and the artist. Neither knows about the other's internals.

This simulation is based on the Smoothed Particle Hydrodynamics (SPH) parts of ESC202 at UZH of spring 2022.

File created on 2026-10-21 by Daniel Walther @radRoy on GitHub.
"""

import itertools
import os
import re
import time

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy.spatial import KDTree

from old_code.sph_post_animation_pre_force import drift1


class Particles:
    """'Particles' are meant to be *parcels* (abstract portions of a whole) of the simulated matter.
    This is conceptually based on the Lagrangian method used for physical equations of motion."""

    def __init__(self, simulate: str = 'hydrodynamics', n: int = 50, dt: float = 0.02, dimensions: tuple[int] = (4, 1), seed: int = 0, k: int = 8,
                 mode:str = 'random', n_centre_particles: int | None = None, jitter: float | None = None):

        # constants
        self.dimensions = np.array(dimensions, dtype=float)
        self.simulate = simulate
        self.n_particles = n
        self.dt = dt
        self.k = k
        # seed for random number generation
        np.random.seed(20261101)

        # physical properties
        self.time = 0.0  # elapsed simulation time in seconds
        self.step = 0  # number of calculated timesteps
        self.timesteps = 0
        self.positions_ = None  # self class variable must exist in __init__ before assigning values to it
        if simulate == 'gravity':
            n_centre = n_centre_particles if n_centre_particles is not None else (0 if mode == 'sinus' else max(1, n // 10))
        else:
            n_centre = 0
        self.initiate_particle_positions(mode, simulate=simulate, n_centre=n_centre, jitter=jitter)
        if simulate == 'gravity':
            self.k = self.n_particles
        self.velocities_ = None  # self class variable must exist in __init__ before assigning values to it
        self.initiate_particle_velocities(simulate)
        self.densities = np.zeros(self.n_particles)  # previously aka Particle.rho
        self.distances = None  # used in (k) nearest neighbour search
        self.indices = None  # used in (k) nearest neighbour search

        # physical variables and thermodynamic state
        self.energies = np.ones(self.n_particles)  # specific internal thermal energy e
        self.energies_prediction = np.ones(self.n_particles)  # predicted internal energy e_pred for mid-step
        self.energies_derivative = np.zeros(self.n_particles)  # internal energy rate of change de/dt
        self.acceleration_ = np.zeros((self.n_particles, 2))  # hydrodynamic acceleration dv/dt
        self.c_sound = np.zeros(self.n_particles)  # speed of sound (particle wise? TODO Explain)
        self.pressures = np.zeros(self.n_particles)  # thermodynamic pressure P

        # 1st order Euler approximations
        self.velocities_prediction_ = np.zeros((self.n_particles, 2))  # predictor velocity for leapfrog (x, y)

        # equation of state and artificial viscosity parameters
        self.gamma = 5.0 / 3.0  # TODO Explain and comment meaning of these variables
        self.alpha = 1.0  # TODO Explain and comment meaning of these variables
        self.beta = 2.0  # TODO Explain and comment meaning of these variables

        # Initialise simulation with bootstrapping function calls (sph5 page 4)
        self.k_nearest_neighbours()
        self.density_monaghan()
        self.drift1(dt=0.0)
        if simulate == 'gravity':
            self.calc_gravity_force()
        else:
            self.calcforce()

    def initiate_particle_positions(self, mode:str, simulate:str = 'hydrodynamics', n_centre: int = 0, jitter: float | None = None):

        if mode == 'random':
            self.positions_ = np.random.random((self.n_particles, 2)) * self.dimensions  # previously aka Particle.r_

        elif mode == 'sinus':
            positions = []
            for i in range(self.n_particles):
                positions.append([i * self.dimensions[0] / self.n_particles,
                                  self.dimensions[1] / 2 + self.dimensions[1] / 5 * np.sin(
                                      i * self.dimensions[0] / self.n_particles)])
            self.positions_ = np.array(positions)

            # add jitter to sinus initial positions in gravity mode
            if simulate == 'gravity' or jitter is not None:
                jitter_val = 0.05 if jitter is None else jitter
                if jitter_val > 0:
                    jitter_offsets = np.random.uniform(-jitter_val, jitter_val, size=self.positions_.shape)
                    self.positions_ = (self.positions_ + jitter_offsets) % self.dimensions

        else:
            raise ValueError(f"Invalid mode: {mode}")

        if simulate == 'gravity' and n_centre > 0:
            centre_positions = np.full((n_centre, 2), self.dimensions / 2.0)
            self.positions_ = np.vstack([self.positions_, centre_positions])
            self.n_particles = len(self.positions_)
            self.k = self.n_particles

    def initiate_particle_velocities(self, simulate):

        if simulate == 'hydrodynamics':
            self.velocities_ = np.random.randn(self.n_particles, 2) * 4 + np.array([2, 0])  # previously aka Particle.v_

        elif simulate == 'gravity':
            self.velocities_ = np.zeros((self.n_particles, 2))

        else:
            raise ValueError(f"Invalid simulate option: '{simulate}'. Valid options are: 'hydrodynamics', 'gravity'")

    def k_nearest_neighbours(self):
        """Find the k-nearest neighbours using vectorized scipy.spatial.KDTree (K-Dimensional Tree) spatial indexing
        with periodic boundaries.

        :return: `tuple` (distances, indices) with shapes (N, k).
        """

        tree = KDTree(self.positions_, boxsize=self.dimensions)
        self.distances, self.indices = tree.query(self.positions_, k=self.k)

        return self.distances, self.indices

    def density_monaghan(self):  # calculates self.densities previously aka Particle.rho
        """Compute local mass density for all particles using the 2D Monaghan cubic spline kernel.

        Evaluates densities across all particles in a fully vectorized SIMD pass using precomputed
        or freshly queried periodic KDTree neighbour distances.

        :param k: Optional int Number of nearest neighbours to evaluate.
        :return: np.ndarray Array of particle densities with shape (N,).
        """

        h = self.distances[:, -1]  # smoothing length per particle: shape (N,)
        h_safe = np.where(h > 0.0, h, 1e-12)[:, None]  # shape (N, 1) for broadcasting

        q = self.distances / h_safe  # shape (N, k)
        sigma = 40.0 / (7.0 * np.pi)
        m = 1.0  # particle mass

        w_kernel = np.zeros_like(q)
        mask1 = (q >= 0.0) & (q < 0.5)
        mask2 = (q >= 0.5) & (q <= 1.0)
        w_kernel[mask1] = 6.0 * (q[mask1] ** 3) - 6.0 * (q[mask1] ** 2) + 1.0
        w_kernel[mask2] = 2.0 * ((1.0 - q[mask2]) ** 3)

        kernel_values = (sigma / (h_safe ** 2)) * w_kernel
        self.densities = np.sum(m * kernel_values, axis=1)

        return self.densities


    def drift1(self, dt:float):
        """Advance particle positions in-place, dt is expected to be half a time step."""
        self.positions_ += self.velocities_ * dt
        self.positions_ %= self.dimensions  # Implementation of periodic boundary conditions
        self.velocities_prediction_ = self.velocities_ + self.acceleration_ * dt  # predicted mid-step velocity

        # energies are particle wise specific thermal energy in <unit> TODO find the unit
        self.energies_prediction = self.energies + self.energies_derivative * dt

        # Specific thermal energy cannot be negative physically (e >=\ge 0). Numerical integration steps during rapid fluid expansion can otherwise overshoot and push energy below zero.
        # Calculating the speed of sound in calcsound() requires evaluating a square root with energies_prediction in it.
        self.energies_prediction = np.maximum(self.energies_prediction, 0.0)

    def drift2(self, dt:float):
        """Completes the second half-step position advancement (sph5 page 5)."""
        self.positions_ += self.velocities_ * dt
        self.positions_ %= self.dimensions  # Implementation of periodic boundary conditions

    def kick(self, dt:float):
        """Applies full-step updates to the velocities and internal energies (sph5 page 5)."""
        self.velocities_ += self.acceleration_ * dt  # full-step velocity update
        self.energies += self.energies_derivative * dt  # full-step internal energy update
        self.energies = np.maximum(self.energies, 0.0)  # clamp to non-negative energy

    def calcsound(self):
        """Calculate thermodynamic pressure and speed of sound using predicted quantities (sph5 page 4)."""
        self.pressures = (self.gamma - 1.0) * self.densities * self.energies_prediction  # ideal gas equation of state: P = (gamma - 1) * rho * e
        self.c_sound = np.sqrt(np.maximum(self.gamma * (self.gamma - 1.0) * self.energies_prediction, 0.0))  # sound speed: c = sqrt(gamma * (gamma - 1) * e)

    def nn_sphforce(self):
        """Compute hydrodynamic accelerations and internal energy rates of change (sph5 pages 1-3)."""
        neighbour_indices = self.indices[:, 1:self.k]  # exclude self (col 0), shape: (N, k-1)
        neighbour_positions = self.positions_[neighbour_indices]  # shape: (N, k-1, 2)
        own_position = self.positions_[:, None, :]  # shape: (N, 1, 2)

        # Minimum image convention displacement vector: r_ab = r_a - r_b  # TODO Explain 'image convention'
        disp = own_position - neighbour_positions  # shape: (N, k-1, 2)
        disp = (disp + 0.5 * self.dimensions) % self.dimensions - 0.5 * self.dimensions  # wrap periodic displacement

        # Scalar distance r_ab
        r = np.linalg.norm(disp, axis=-1)  # shape: (N, k-1)
        r_safe = np.maximum(r, 1e-12)  # avoid division by zero (distance between particles can not be zero)

        # Smoothing lengths
        h_a = self.distances[:, -1, None]  # smoothing length of particle a: shape (N, 1)
        h_b = self.distances[neighbour_indices, -1]  # smoothing length of neighbour b: shape (N, k-1)
        h_a_safe = np.maximum(h_a, 1e-12)  # (distance to k nearest particles can not be zero)
        h_b_safe = np.maximum(h_b, 1e-12)  # (distance to k nearest particles can not be zero)

        # Monaghan cubic spline kernel gradients
        sigma = 40.0 / (7.0 * np.pi)  # TODO Explain

        q_a = r / h_a_safe  # normalized distance for particle a, weighting each neighbour particle's influence on the focus particle's mass density approximation
        dw_dq_a = np.zeros_like(q_a)  # TODO Explain
        m1_a = (q_a >= 0.0) & (q_a < 0.5)  # TODO Explain
        m2_a = (q_a >= 0.5) & (q_a <= 1.0)  # TODO Explain
        dw_dq_a[m1_a] = 18.0 * (q_a[m1_a] ** 2) - 12.0 * q_a[m1_a]  # TODO Explain
        dw_dq_a[m2_a] = -6.0 * ((1.0 - q_a[m2_a]) ** 2)  # TODO Explain
        grad_w_scalar_a = (sigma / (h_a_safe ** 3)) * dw_dq_a  # |grad W(r_ab, h_a)|  # TODO Explain

        # TODO Explain, maybe revisit lecture notes. See gather scatter part of sph5.
        # Explanatory comments of above (q_a, ...) analogously apply to this code section.
        q_b = r / h_b_safe  # normalized distance for neighbour b
        dw_dq_b = np.zeros_like(q_b)
        m1_b = (q_b >= 0.0) & (q_b < 0.5)
        m2_b = (q_b >= 0.5) & (q_b <= 1.0)
        dw_dq_b[m1_b] = 18.0 * (q_b[m1_b] ** 2) - 12.0 * q_b[m1_b]
        dw_dq_b[m2_b] = -6.0 * ((1.0 - q_b[m2_b]) ** 2)
        grad_w_scalar_b = (sigma / (h_b_safe ** 3)) * dw_dq_b  # |grad W(r_ab, h_b)|

        # TODO Explain
        # Symmetrized kernel gradient: grad_a W_ab = 0.5 * (grad_a W(r_ab, h_a) + grad_a W(r_ab, h_b))
        grad_scalar = 0.5 * (grad_w_scalar_a + grad_w_scalar_b)
        unit_vec = disp / r_safe[:, :, None]  # unit displacement vector
        grad_w_ab = grad_scalar[:, :, None] * unit_vec  # vector kernel gradient grad_a W_ab: shape (N, k-1, 2)

        # TODO Explain
        # Thermodynamic properties for pairs
        rho_a = np.maximum(self.densities[:, None], 1e-12)
        rho_b = np.maximum(self.densities[neighbour_indices], 1e-12)
        p_a = self.pressures[:, None]
        p_b = self.pressures[neighbour_indices]
        c_a = self.c_sound[:, None]
        c_b = self.c_sound[neighbour_indices]

        # TODO Explain
        # Artificial viscosity Pi_ab (sph5 page 3)
        v_a = self.velocities_prediction_[:, None, :]
        v_b = self.velocities_prediction_[neighbour_indices]
        v_ab = v_a - v_b  # relative predicted velocity v_a - v_b

        # TODO Explain
        v_dot_r = np.sum(v_ab * disp, axis=-1)  # (v_a - v_b) . r_ab
        h_bar = 0.5 * (h_a + h_b)  # mean smoothing length
        c_bar = 0.5 * (c_a + c_b)  # mean sound speed
        rho_bar = 0.5 * (rho_a + rho_b)  # mean density
        eta_sq = 0.01 * (h_bar ** 2)  # prevent singularity when r -> 0

        # TODO Explain
        mu_ab = (h_bar * v_dot_r) / (r ** 2 + eta_sq)  # Monaghan-Gingold viscosity term
        pi_ab = np.where(v_dot_r < 0.0,
                         (-self.alpha * c_bar * mu_ab + self.beta * (mu_ab ** 2)) / rho_bar,
                         0.0)  # active only under compression

        # TODO Explain
        # F_ab = P_a / rho_a^2 + P_b / rho_b^2 + Pi_ab
        f_ab = (p_a / (rho_a ** 2)) + (p_b / (rho_b ** 2)) + pi_ab  # symmetric pressure and viscosity factor

        # TODO Why not move this to Particle attributes? (init section)
        m = 1.0  # particle mass

        # Negation of term on the right (accelerate away from high density = against density gradient)
        self.acceleration_ = - np.sum(m * f_ab[:, :, None] * grad_w_ab, axis=1)  # sum pairwise forces

        # TODO Explain
        # Benz formulation: de_a / dt = sum_b m_b * (P_a / rho_a^2 + 0.5 * Pi_ab) * (v_a - v_b) . grad_a W_ab
        v_dot_grad = np.sum(v_ab * grad_w_ab, axis=-1)  # (v_a - v_b) . grad_a W_ab
        energy_term = (p_a / (rho_a ** 2) + 0.5 * pi_ab) * v_dot_grad  # work done by pressure and viscosity
        self.energies_derivative = np.sum(m * energy_term, axis=1)  # thermal energy rate of change

    def calcforce(self):
        """Evaluates mass densities, thermodynamic properties, hydrodynamic forces, and energy rates using the predicted quantities."""
        self.k_nearest_neighbours()
        self.density_monaghan()
        self.calcsound()  # pressure and sound speed from predicted state
        # TODO Explain How speed of sound can be locally different, like sound moving not equally fast through different media, maybe. What is the scale of variation, here?

        # TODO Explain physical concept & meaning of internal energy rate
        self.nn_sphforce()  # accelerations and internal energy rates

    def calc_gravity_force(self):
        """Evaluates mass densities and pairwise gravitational forces using predicted positions."""
        self.k_nearest_neighbours()
        self.density_monaghan()

        # Column 0 corresponds to self-interaction (distance 0); columns 1:k are neighbours
        neighbour_indices = self.indices[:, 1:self.k]  # shape: (N, k-1)
        neighbour_positions = self.positions_[neighbour_indices]  # shape: (N, k-1, 2)
        own_position = self.positions_[:, None, :]  # shape: (N, 1, 2)

        # Shortest displacement vector with periodic boundary conditions (minimum image convention)
        displacement_vector = neighbour_positions - own_position  # shape: (N, k-1, 2)
        displacement_vector = (displacement_vector + 0.5 * self.dimensions) % self.dimensions - 0.5 * self.dimensions

        # Squared Euclidean distance
        r_sq = np.sum(displacement_vector ** 2, axis=-1, keepdims=True)  # shape: (N, k-1, 1)
        r_sq = np.maximum(r_sq, 1e-6)

        # Pairwise attraction force (gravitation-like dummy equation)
        forces_attraction = (9.81 / (2000 * r_sq ** 0.5)) * displacement_vector  # shape: (N, k-1, 2)
        forces = forces_attraction
        self.acceleration_ = np.sum(forces, axis=1)  # gravitational accelerations: shape (N, 2)
        self.energies_derivative = np.zeros(self.n_particles)  # no thermal energy rate in pure gravity

    def advance_gravity_simulation(self):
        """Execute one simulation integration step using the Leapfrog predictor-corrector scheme with gravity."""
        self.drift1(dt=self.dt / 2.0)  # half-step drift and state prediction
        self.calc_gravity_force()  # mid-step gravitational force evaluation
        self.kick(dt=self.dt)  # full-step velocity kick
        self.drift2(dt=self.dt / 2.0)  # second half-step position drift
        self.time += self.dt
        self.step += 1
        self.timesteps += 1

    advance_gravitational_positions = advance_gravity_simulation

    def advance_hydrodynamics_simulation(self):  # previously aka advance_simulation()
        """Execute one simulation integration step using the Leapfrog predictor-corrector scheme."""
        self.drift1(dt=self.dt / 2.0)  # half-step drift and state prediction
        self.calcforce()  # mid-step force and energy derivative evaluation
        self.kick(dt=self.dt)  # full-step velocity and internal energy kick
        self.drift2(dt=self.dt / 2.0)  # second half-step position drift
        self.time += self.dt
        self.step += 1
        self.timesteps += 1

    advance_simulation = advance_hydrodynamics_simulation



def get_unique_video_path(filename: str, default_dir: str = "outputs") -> str:
    """Ensure target directory exists and return a unique file path with incrementing suffix if file exists."""
    if not os.path.dirname(filename):
        filename = os.path.join(default_dir, filename)

    target_dir = os.path.dirname(filename)
    if target_dir:
        os.makedirs(target_dir, exist_ok=True)

    if not os.path.exists(filename):
        return filename

    dir_name, base_name = os.path.split(filename)
    stem, ext = os.path.splitext(base_name)

    match = re.search(r"^(.*)_(\d+)$", stem)
    if match:
        prefix = match.group(1)
        counter = int(match.group(2)) + 1
        width = max(2, len(match.group(2)))
    else:
        prefix = stem
        counter = 1
        width = 2

    while True:
        candidate = os.path.join(dir_name, f"{prefix}_{counter:0{width}d}{ext}")
        if not os.path.exists(candidate):
            return candidate
        counter += 1


class MplFuncRenderer:
    """Matplotlib FuncAnimation renderer implementing Renderer2D with hardware blitting.

    What does the renderer do?
    The renderer manages the visual lifecycle and presentation timing of the simulation:
    - Decoupled Graphics Pipeline: It abstracts Matplotlib details away from the physics model.
    - Performance Optimization: Employs a single `PathCollection` artist (via scatter) to render
      all N particles with colormapped densities in a single vectorized draw call.
    - Blitting (Hardware Acceleration): Pre-renders the static canvas background once. During
      animation frames, only the pixels occupied by moving particles are updated, maximizing
      rendering framerates.
    """

    def __init__(self, *, dimensions, interval=0, marker_size=3.0,
                 figsize=(7, 7), dpi=100,
                 bg="#0b0b12", fg="#8fd3ff", cmap="viridis",
                 axis_off=True, aspect='equal', window_title: str | None = None):
        """Initialize the Matplotlib FuncAnimation renderer with viewport settings and styling.

        :param dimensions: (width, height) domain dimensions defining coordinate bounds.
        :param interval: Delay between animation frames in milliseconds (0 for unthrottled maximum fps).
        :param marker_size: Point marker size for particles.
        :param figsize: Matplotlib figure dimensions (width, height) in inches.
        :param dpi: Figure resolution in dots per inch.
        :param bg: Background hex color code.
        :param fg: Particle marker foreground hex color code.
        :param cmap: Matplotlib colormap name or Colormap instance (default 'viridis').
        :param axis_off: If True, hide axes ticks and spines to minimize visual clutter.
        :param aspect: Aspect ratio setting for axes (default 'equal' to preserve physical geometry).
        :param window_title: Optional title string for the animation figure window.
        """
        self.bounds = (0, dimensions[0], 0, dimensions[1])
        self.interval = interval
        self.marker_size = marker_size
        self.figsize = figsize
        self.dpi = dpi
        self.bg = bg
        self.cmap = cmap
        self.axis_off = axis_off
        self.aspect = aspect
        self.window_title = window_title
        self.fig = None
        self.ax = None
        self.ani = None
        self.artist = None
        self.fps_text = None
        self.time_text = None
        self.step_text = None
        self.sim = None
        self.positions = None
        self.densities = None

    def mount(self, particles, densities=None):
        """Set up the Matplotlib figure, axes, and animated PathCollection artist with initial particle positions and
        densities.

        :param particles: Particles instance or np.ndarray of particle positions with shape (N, 2).
        :param densities: Optional np.ndarray of particle densities with shape (N,).
        """
        if hasattr(particles, "positions_"):
            self.sim = particles
            self.positions = particles.positions_
            self.densities = getattr(particles, "densities", None)
        else:
            self.sim = None
            self.positions = particles
            self.densities = densities

        if self.densities is None:
            self.densities = np.zeros(len(self.positions))

        xmin, xmax, ymin, ymax = self.bounds

        self.fig, self.ax = plt.subplots(figsize=self.figsize, dpi=self.dpi)
        if self.window_title and self.fig.canvas.manager is not None and hasattr(self.fig.canvas.manager, "set_window_title"):
            try:
                self.fig.canvas.manager.set_window_title(self.window_title)
            except Exception:
                pass
        self.fig.patch.set_facecolor(self.bg)
        self.ax.set_facecolor(self.bg)
        self.fig.subplots_adjust(left=0, bottom=0, right=1, top=1)     # no padding to composite

        # Set aspect BEFORE the first draw: it can resize the axes box, and
        # the blit background is captured from that box.
        self.ax.set_aspect(aspect=self.aspect)

        # Frozen viewport. Autoscaling would invalidate the blit background
        # cache and force a full redraw every frame.
        self.ax.set_xlim(xmin, xmax)
        self.ax.set_ylim(ymin, ymax)
        if self.axis_off:
            self.ax.set_axis_off()

        # Scatter artist mapping particle densities to colormap (default viridis)
        s = self.marker_size ** 2
        self.artist = self.ax.scatter(
            self.positions[:, 0], self.positions[:, 1],
            s=s,
            c=self.densities,
            cmap=self.cmap,
            animated=True,                   # blit redraws ONLY this
        )

        # Discrete FPS indicator in the top right corner with a slight shadow
        self.fps_text = self.ax.text(
            0.98, 0.98,
            "",
            transform=self.ax.transAxes,
            ha="right",
            va="top",
            fontsize=9,
            color='#fff',
            alpha=1,
            animated=True
        )

        # Discrete time indicator in the top left corner in seconds
        self.time_text = self.ax.text(
            0.02, 0.98,
            "",
            transform=self.ax.transAxes,
            ha="left",
            va="top",
            fontsize=9,
            color='#fff',
            alpha=1,
            animated=True
        )

        # Discrete timestep indicator in the bottom left corner
        self.step_text = self.ax.text(
            0.02, 0.02,
            "",
            transform=self.ax.transAxes,
            ha="left",
            va="bottom",
            fontsize=9,
            color='#fff',
            alpha=1,
            animated=True
        )

    def present(self):
        """Update PathCollection artist coordinates and colors with the current simulation state."""
        if self.sim is not None:
            self.positions = self.sim.positions_
            self.densities = self.sim.densities

        self.artist.set_offsets(self.positions)
        if self.densities is not None and len(self.densities) == len(self.positions):
            self.artist.set_array(self.densities)
            min_d, max_d = float(np.min(self.densities)), float(np.max(self.densities))
            if min_d < max_d:
                self.artist.set_clim(min_d, max_d)

    def run(self, advance, frames=None, save_video: bool = False, video_filename: str = "simulation.mp4", fps: float | int | None = None):
        """Start the animation loop or save video using Matplotlib's FuncAnimation.

        Controls the event loop and coordinates physics calculation with graphics refresh.
        On every frame tick:
        1. Calls `advance()` to let the simulation integrate equations of motion.
        2. Calls `present()` to refresh artist coordinates.
        3. Returns an iterable containing updated artists so Matplotlib blitting
           redraws only the updated regions over the cached background.

        :param advance: Callable that advances the simulation state by one time step.
        :param frames: Iterable producing frame indices or int number of frames.
        :param save_video: If True, save animation as a video file instead of live display.
        :param video_filename: Output video file path.
        :param fps: Frames per second for video output or FPS text display (defaults to 1.0 / dt).
        """
        if fps is None:
            fps = (1.0 / self.sim.dt) if (self.sim is not None and getattr(self.sim, "dt", 0) > 0) else 30
        if isinstance(fps, float) and abs(fps - round(fps)) < 1e-5:
            fps = int(round(fps))

        if frames is None:
            frames = 300 if save_video else itertools.count()

        last_time = None
        fps_val = None

        def tick(_frame):
            nonlocal last_time, fps_val
            advance()
            self.present()

            if save_video:
                if self.fps_text is not None:
                    self.fps_text.set_text(f"{round(fps)} FPS")
            else:
                now = time.perf_counter()
                if last_time is not None:
                    dt = now - last_time
                    if dt > 0:
                        inst_fps = 1.0 / dt
                        fps_val = inst_fps if fps_val is None else 0.9 * fps_val + 0.1 * inst_fps
                        if self.fps_text is not None:
                            self.fps_text.set_text(f"{round(fps_val)} FPS")
                last_time = now

            if self.time_text is not None:
                sim_time = getattr(self.sim, "time", None)
                if sim_time is None:
                    sim_time = (_frame + 1) * getattr(self.sim, "dt", 0.02)
                self.time_text.set_text(f"{sim_time:.2f} s")

            if self.step_text is not None:
                sim_step = getattr(self.sim, "step", None)
                if sim_step is None:
                    sim_step = _frame + 1
                self.step_text.set_text(f"Step: {sim_step}")

            # Matplotlib blitting requires returning an iterable of updated artists
            # so the engine knows which screen regions need redrawing.
            artists = [self.artist]
            if self.fps_text is not None:
                artists.append(self.fps_text)
            if self.time_text is not None:
                artists.append(self.time_text)
            if self.step_text is not None:
                artists.append(self.step_text)
            return tuple(artists)

        self.ani = FuncAnimation(
            self.fig, tick,
            frames=frames,
            interval=self.interval,
            blit=True,
            cache_frame_data=False,
            repeat=False,
        )
        if save_video:
            resolved_video_filename = get_unique_video_path(video_filename)
            self.ani.save(resolved_video_filename, fps=fps, writer="ffmpeg")
            plt.close(self.fig)
        else:
            plt.show()


def main(simulate_motion_by:str='hydrodynamics', n_particle_parcels:int=100, dt:float=0.02, dims=(4, 1), frame_duration: int = 16, marker_size:float=3.0, k_neighbours:int=32, mode:str='random', create_video:bool=False, video_filename:str="simulation.mp4", video_dir:str="outputs", video_frames:int=300, video_fps:float|int|None=None, video:bool=False, window_title:str|None=None, n_centre_particles:int|None=None, video_duration:float|None=None, jitter:float|None=None, **kwargs):
    """Set up and run the particle simulation and Matplotlib animation or video output.

    Orchestrates the simulation lifecycle:
    1. Instantiates the physics ensemble (`Particles`).
    2. Instantiates the visualization renderer (`MplFuncRenderer`).
    3. Mounts the particle simulation into the renderer (`mount`).
    4. Starts either the live animation loop or renders to video (`run`).

    :param simulate_motion_by: Physical simulation type ('hydrodynamics' or 'gravity').
    :param n_particle_parcels: `int` Number of particles to simulate.
    :param dt: `float` Integration time step.
    :param dims: `tuple` Domain dimensions (width, height).
    :param frame_duration: `int` Frame interval in milliseconds (0 for maximum speed).
    :param marker_size: `float` Display marker size of particles.
    :param k_neighbours: `int` desired number of nearest neighbours to consider for acceleration computation. Smaller values
    result in faster computation but less accurate results.
    :param mode: Particle position initialization mode ('random' or 'sinus').
    :param create_video: If True, save a video file instead of running live animation.
    :param video_filename: Path for output video file.
    :param video_dir: Directory where video files are stored (default 'outputs').
    :param video_frames: Number of frames to render when creating a video.
    :param video_fps: Framerate for video creation (defaults to 1.0 / dt to match simulated time 1:1).
    :param video: Alias for create_video.
    :param window_title: Optional custom window title for the animation figure.
    :param n_centre_particles: Optional int number of central particles to add in gravity mode.
    :param video_duration: Optional duration of video in seconds (computes video_frames as video_duration * video_fps).
    :param jitter: Optional float jitter magnitude to add to particle positions.
    """

    valid_simulations = ['hydrodynamics', 'gravity']
    if simulate_motion_by not in valid_simulations:
        raise ValueError(f"Invalid simulate_motion_by '{simulate_motion_by}'. Valid choices: {', '.join(valid_simulations)}")

    valid_modes = ['random', 'sinus']
    if mode not in valid_modes:
        raise ValueError(f"Invalid mode '{mode}'. Valid modes are: {', '.join(valid_modes)}")

    if simulate_motion_by == 'gravity':
        if k_neighbours != n_particle_parcels:
            k_neighbours = n_particle_parcels
            print(f'Warning: Number of nearest neighbour parcels k_neighbours has been forced to be the number of mass particles n_particle_parcels ({n_particle_parcels}) due to gravity being chosen as the physical equations of motion.')

    if k_neighbours <= 0:
        raise ValueError("k must be greater than 0 (Particles can not have 0 or less nearest particles)")

    if k_neighbours > n_particle_parcels:
        k_neighbours = n_particle_parcels  # prevents search for more neighbours (k) than particeles existing (n)
        print(f"Warning: Number of nearest neighbour parcels k_neighbours exceeds number of parcels n, setting k_neighbours to n_particle_parcels ({n_particle_parcels}).")

    is_video = create_video or video or kwargs.get('save_video', False)
    if video_fps is None:
        video_fps = int(round(1.0 / dt)) if abs(1.0 / dt - round(1.0 / dt)) < 1e-5 else 1.0 / dt
    if video_duration is None:
        video_duration = kwargs.get('video_duration', None)
    if video_duration is not None:
        video_frames = int(round(video_duration * video_fps))

    # own attempt at animating a particle with teleporting boundaries
    sim = Particles(simulate=simulate_motion_by, n=n_particle_parcels, dt=dt, dimensions=dims, k=k_neighbours, mode=mode, n_centre_particles=n_centre_particles, jitter=jitter)
    n_particle_parcels = sim.n_particles
    k_neighbours = sim.k

    if window_title is None:
        sim_name = "Gravity" if simulate_motion_by == 'gravity' else "SPH"
        window_title = f"{sim_name} Simulation ({n_particle_parcels} parcels, {dt} time step, {k_neighbours} nearest neighbours)"

    renderer = MplFuncRenderer(
        dimensions=dims,  # The x, y dimensions of the simulation (e.g., dimensions=(4, 3))
        interval=frame_duration,  # milliseconds, 0 = as fast as the backend allows; try 16 for ~60 fps
        marker_size=marker_size,  # size of the particle markers in the simulation
        figsize=dims,  # resolution of the simulation (units?)
        cmap="viridis",  # colormap mpl viridis to visualise particle mass density
        window_title=window_title
    )
    renderer.mount(particles=sim)

    advance_fn = sim.advance_hydrodynamics_simulation if simulate_motion_by == 'hydrodynamics' else sim.advance_gravity_simulation

    if is_video:
        target_video_path = get_unique_video_path(video_filename, default_dir=video_dir)
        renderer.run(advance=advance_fn, frames=video_frames, save_video=True, video_filename=target_video_path, fps=video_fps)
    else:
        renderer.run(advance=advance_fn, frames=itertools.count(), save_video=False)


if __name__ == "__main__":

    # TODO Add SI-units to every physical quantity and equation

    # dt > 0.01 is usually not stable in v0.2.0.dev0
    # mode can be: random, sinus

    # KEEP SPH GENERATION TEMPLATE
    # SPH simulation
    video_duration_sph = 20  # seconds
    dt_sph = 0.005  # seconds
    mode_sph = 'random'
    k_neighbours_sph = 64
    main(
        simulate_motion_by='hydrodynamics',
        n_particle_parcels=400,
        dt=dt_sph,
        dims=(8, 4.5),
        frame_duration=0,
        marker_size=5,
        k_neighbours=k_neighbours_sph,
        mode=mode_sph,
        create_video=True,
        video_duration=video_duration_sph,
        video_filename=f"hydrodynamics_leapfrog_{k_neighbours_sph}neighbours_{1//dt_sph}fps.mp4",
        video_dir="outputs",
    )

    # KEEP GRAVITY GENERATION TEMPLATE
    # gravity simulations
    video_duration_gravity = 30  # seconds
    dt_gravity = 0.01  # seconds
    mode_gravity = 'random'
    n_particles_gravity = 400
    k_neighbours_gravity = n_particles_gravity
    main(
        simulate_motion_by='gravity',
        n_particle_parcels=400,
        dt=0.01,
        dims=(12, 6.75),
        frame_duration=0,
        marker_size=5,
        k_neighbours=k_neighbours_gravity,
        mode=mode_gravity,
        create_video=True,
        video_duration=video_duration_gravity,
        video_filename=f"gravity_leapfrog_{k_neighbours_gravity}neighbours_{1 // dt_gravity}fps.mp4",
        video_dir="outputs",
    )

    # KEEP GRAVITY GENERATION TEMPLATE
    # gravity simulations
    video_duration_gravity = 30  # seconds
    dt_gravity = 0.035  # seconds
    mode_gravity = 'sinus'
    n_particles_gravity = 400
    k_neighbours_gravity = n_particles_gravity
    main(
        simulate_motion_by='gravity',
        n_particle_parcels=n_particles_gravity,
        dt=dt_gravity,
        dims=(12, 6.75),
        frame_duration=0,
        marker_size=5,
        k_neighbours=k_neighbours_gravity,
        mode=mode_gravity,
        jitter=0.25,
        create_video=True,
        video_duration=video_duration_gravity,
        video_filename=f"gravity_leapfrog_{k_neighbours_gravity}neighbours_{1 // dt_gravity}fps.mp4",
        video_dir="outputs",
    )
