"""Kinematic rover exercise. Prints simulated commands and pose as CSV."""

import csv
import sys
from math import cos, sin

WHEEL_RADIUS_M = 0.033
TRACK_WIDTH_M = 0.160
TICK_MS = 50
COMMAND_TIMEOUT_MS = 250
RUN_MS = 1500


def body_velocity(left_rad_s, right_rad_s):
    left = WHEEL_RADIUS_M * left_rad_s
    right = WHEEL_RADIUS_M * right_rad_s
    return (left + right) / 2, (right - left) / TRACK_WIDTH_M


def advance(x, y, heading, speed, yaw_rate):
    duration = TICK_MS / 1000
    next_heading = heading + yaw_rate * duration
    if abs(yaw_rate) < 1e-12:
        return x + speed * duration * cos(heading), y + speed * duration * sin(heading), heading
    radius = speed / yaw_rate
    next_x = x + radius * (sin(next_heading) - sin(heading))
    next_y = y + radius * (cos(heading) - cos(next_heading))
    return next_x, next_y, next_heading


def scenario_rows(name, wheel_command, last_message_ms):
    x = y = heading = 0.0
    received_ms = 0
    for time_ms in range(0, RUN_MS + TICK_MS, TICK_MS):
        if time_ms <= last_message_ms:
            received_ms = time_ms
        age_ms = time_ms - received_ms
        expired = age_ms >= COMMAND_TIMEOUT_MS
        left, right = (0, 0) if expired else wheel_command
        speed, yaw_rate = body_velocity(left, right)
        yield (
            name, time_ms, age_ms, int(expired), left, right,
            f"{speed:.6f}", f"{yaw_rate:.6f}",
            f"{x:.6f}", f"{y:.6f}", f"{heading:.6f}",
        )
        x, y, heading = advance(x, y, heading, speed, yaw_rate)


def main():
    writer = csv.writer(sys.stdout, lineterminator="\n")
    writer.writerow((
        "scenario", "time_ms", "command_age_ms", "expired", "left_target_rad_s",
        "right_target_rad_s", "speed_m_s", "yaw_rate_rad_s", "x_m", "y_m", "heading_rad",
    ))
    writer.writerows(scenario_rows("straight", (10, 10), RUN_MS))
    writer.writerows(scenario_rows("left_turn", (8, 12), RUN_MS))
    writer.writerows(scenario_rows("timeout", (8, 12), 1000))


if __name__ == "__main__":
    main()
