"""Tennimechanics: synthetic inputs, simulated vacuum trajectory (SI units)."""
import json
import math


def simulate(position=(0.0, -10.0, 1.0), velocity=(0.0, 20.0, 3.0),
             radius=0.033, gravity=9.81, dt=0.01):
    """Explicit Euler integration; linear interpolation of first ground contact.

    Frame: right-handed court XYZ, Z up. No drag, spin, net or bounce.
    """
    if len(position) != 3 or len(velocity) != 3:
        raise ValueError('position and velocity must have three components')
    values = (*position, *velocity, radius, gravity, dt)
    if not all(math.isfinite(v) for v in values):
        raise ValueError('inputs must be finite')
    if radius <= 0 or gravity <= 0 or dt <= 0 or position[2] <= radius:
        raise ValueError('positive radius/gravity/dt and initial height > radius required')
    x, y, z = position
    vx, vy, vz = velocity
    t = 0.0
    samples = [[t, x, y, z]]
    # Hard bound avoids unbounded execution for unreasonable parameter choices.
    for _ in range(100000):
        nx, ny, nz = x + vx * dt, y + vy * dt, z + vz * dt
        if nz <= radius:
            fraction = (z - radius) / (z - nz)
            samples.append([t + fraction * dt,
                            x + fraction * (nx - x),
                            y + fraction * (ny - y), radius])
            return samples
        t += dt
        x, y, z = nx, ny, nz
        vz -= gravity * dt
        samples.append([t, x, y, z])
    raise ValueError('step limit exceeded; check initial conditions and dt')


def exact_landing(position, velocity, radius=0.033, gravity=9.81):
    """Analytic reference for a ball initially above the ground."""
    vz = velocity[2]
    root = math.sqrt(vz * vz + 2 * gravity * (position[2] - radius))
    time = ((vz + root) / gravity if vz >= 0 else
            2 * (position[2] - radius) / (root - vz))
    return [time, position[0] + velocity[0] * time,
            position[1] + velocity[1] * time, radius]


if __name__ == '__main__':
    position, velocity = (0.0, -10.0, 1.0), (0.0, 20.0, 3.0)
    trajectory = simulate(position, velocity)
    print(json.dumps({
        'schema_version': '0.1', 'model': 'vacuum-explicit-euler-v1',
        'origin': 'simulated', 'input_origin': 'synthetic',
        'frame_id': 'court_xyz', 'columns': ['time_s', 'x_m', 'y_m', 'z_m'],
        'inputs': {'position_m': position, 'velocity_m_s': velocity,
                   'radius_m': 0.033, 'gravity_m_s2': 9.81, 'dt_s': 0.01},
        'quality_flags': ['educational_model', 'not_validated_against_measurements'],
        'trajectory': trajectory,
        'landing': trajectory[-1],
        'analytic_landing': exact_landing(position, velocity),
    }, ensure_ascii=False, indent=2))
