# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Fixed-step constrained velocity Verlet for a constant diagonal mass matrix."""

from math import fsum, isfinite


def dot(x, y):
    return fsum(a*b for a, b in zip(x, y, strict=True))


def solve(matrix, rhs):
    """Small dense linear solve with partial pivoting."""
    rows = [list(row) + [b] for row, b in zip(matrix, rhs, strict=True)]
    n = len(rows)
    for j in range(n):
        pivot = max(range(j, n), key=lambda i: abs(rows[i][j]))
        rows[j], rows[pivot] = rows[pivot], rows[j]
        if not isfinite(rows[j][j]) or rows[j][j] == 0:
            raise RuntimeError("singular constraint solve")
        for row in rows[j+1:]:
            factor = row[j] / rows[j][j]
            for k in range(j+1, n+1):
                row[k] -= factor*rows[j][k]
    x = [0.0] * n
    for i in reversed(range(n)):
        x[i] = (rows[i][-1] - fsum(rows[i][j]*x[j] for j in range(i+1, n))) / rows[i][i]
    return x


def _norm(values):
    if not all(map(isfinite, values)):
        raise RuntimeError("nonfinite constraint residual")
    return max(map(abs, values), default=0.0)


def _correction(directions, multipliers):
    return tuple(dot(column, multipliers) for column in zip(*directions, strict=True))


def step(q, v, h, mass, force, constraints, gradients, *, tol=1e-13, max_iter=20):
    """Return (q_new, v_new); gradient callback returns one row per constraint."""
    q, v, mass = tuple(q), tuple(v), tuple(mass)
    if not q or len(q) != len(v) or len(q) != len(mass):
        raise ValueError("q, v and mass must have the same nonzero length")
    if not all(map(isfinite, (*q, *v, *mass, h, tol))) or min(mass) <= 0 or tol <= 0 or max_iter < 0:
        raise ValueError("need finite inputs, positive mass and tolerance, and a nonnegative iteration limit")
    if h == 0:
        return q, v
    g0 = tuple(constraints(q))
    rows0 = tuple(tuple(row) for row in gradients(q))
    if len(g0) != len(rows0) or not g0:
        raise ValueError("need one gradient row per constraint")
    if _norm(g0) > tol or _norm(tuple(dot(row, v) for row in rows0)) > tol:
        raise ValueError("initial state must satisfy the position and velocity constraints")
    directions0 = [tuple(a/m for a, m in zip(row, mass, strict=True)) for row in rows0]
    kicked = tuple(u + h*f/(2*m) for u, f, m in zip(v, force(q), mass, strict=True))
    q_free = tuple(x + h*u for x, u in zip(q, kicked, strict=True))
    multipliers = [0.0] * len(g0)
    for attempt in range(max_iter+1):
        shift = _correction(directions0, multipliers)
        q_next = tuple(x + dx for x, dx in zip(q_free, shift, strict=True))
        residual = tuple(constraints(q_next))
        rows1 = tuple(tuple(row) for row in gradients(q_next))
        if len(residual) != len(g0) or len(rows1) != len(g0):
            raise ValueError("constraint count must stay fixed")
        if _norm(residual) <= tol:
            break
        if attempt == max_iter:
            raise RuntimeError("position constraint failed to converge")
        jacobian = [[dot(row, direction) for direction in directions0] for row in rows1]
        update = solve(jacobian, residual)
        multipliers = [a-da for a, da in zip(multipliers, update, strict=True)]

    v_free = tuple(u + dx/h + h*f/(2*m)
                   for u, dx, f, m in zip(kicked, shift, force(q_next), mass, strict=True))
    directions1 = [tuple(a/m for a, m in zip(row, mass, strict=True)) for row in rows1]
    gram = [[dot(row, direction) for direction in directions1] for row in rows1]
    mu = solve(gram, [-dot(row, v_free) for row in rows1])
    v_next = tuple(u + du for u, du in zip(v_free, _correction(directions1, mu), strict=True))
    if _norm(tuple(dot(row, v_next) for row in rows1)) > tol:
        raise RuntimeError("velocity constraint failed to reach tolerance")
    return q_next, v_next
