import math
import random


def _derivatives(t, state, l1: float = 1.0, l2: float = 1.0, m1: float = 1.0, m2: float =1.0, g: float =9.81):
    """
    Computes angular accelerations (d^2*theta/d*st^2) using the Euler-Lagrange equations.
    State vector: [theta1, omega1, theta2, omega2]
    """
    th1, w1, th2, w2 = state
    delta = th1 - th2

    # Common denominator term appearing in both acceleration formulas
    common_den = 2 * m1 + m2 - m2 * math.cos(2 * delta)

    # Angular acceleration for bob 1 (alpha1 = d(omega1)/dt)
    den1 = l1 * common_den
    num1 = (
            -g * (2 * m1 + m2) * math.sin(th1)
            - m2 * g * math.sin(th1 - 2 * th2)
            - 2 * math.sin(delta) * m2 * (w2 ** 2 * l2 + w1 ** 2 * l1 * math.cos(delta))
    )
    alpha1 = num1 / den1

    # Angular acceleration for bob 2 (alpha2 = d(omega2)/dt)
    den2 = l2 * common_den
    num2 = (
            2 * math.sin(delta) * (
            w1 ** 2 * l1 * (m1 + m2)
            + g * (m1 + m2) * math.cos(th1)
            + w2 ** 2 * l2 * m2 * math.cos(delta)
    )
    )
    alpha2 = num2 / den2

    return [w1, alpha1, w2, alpha2]


def _rk4_step(f, t, state, dt):
    """
    4th-order Runge-Kutta (RK4) numerical integrator.
    Sensible practice: simple Euler integration suffers from severe energy drift in chaotic
    systems. RK4 provides high precision and stability while keeping the code compact.
    """
    k1 = f(t, state)
    k2 = f(t + 0.5 * dt, [s + 0.5 * dt * k for s, k in zip(state, k1)])
    k3 = f(t + 0.5 * dt, [s + 0.5 * dt * k for s, k in zip(state, k2)])
    k4 = f(t + dt, [s + dt * k for s, k in zip(state, k3)])

    return [
        s + (dt / 6.0) * (k1_i + 2 * k2_i + 2 * k3_i + k4_i)
        for s, k1_i, k2_i, k3_i, k4_i in zip(state, k1, k2, k3, k4)
    ]


def simulate_double_pendulum(duration_seconds=10.0, fps=60, l1=1.0, l2=1.0):
    """
    Simulates a double pendulum with randomized initial angles for the requested duration.
    Returns a list of Cartesian coordinates [[x1, y1, x2, y2], ...] representing each frame.
    """
    # 1. Randomize initial angles in radians [-pi, pi] to showcase chaotic sensitivity
    initial_theta1 = random.uniform(-math.pi, math.pi)
    initial_theta2 = random.uniform(-math.pi, math.pi)

    # Both bobs start from rest (zero angular velocity)
    state = [initial_theta1, 0.0, initial_theta2, 0.0]

    total_frames = int(duration_seconds * fps)
    dt = 1.0 / fps

    trajectory = []

    # 2. Integrate through time and compute Cartesian positions
    for frame in range(total_frames):
        th1, _, th2, _ = state

        # Convert polar coordinates to Cartesian (x, y) coordinates:
        # In screen/canvas space, +y points downwards, so theta=0 is downward vertical
        x1 = l1 * math.sin(th1)
        y1 = l1 * math.cos(th1)
        x2 = x1 + l2 * math.sin(th2)
        y2 = y1 + l2 * math.cos(th2)

        # Round values to 3 decimal places to minimize JSON payload size over the network
        trajectory.append([round(x1, 3), round(y1, 3), round(x2, 3), round(y2, 3)])

        # Advance physics state
        state = _rk4_step(_derivatives, frame * dt, state, dt)

    return trajectory
