"""Write a synthetic 300-second candump log from truth.dbc, with OBD-II speed and RPM replies as references.

The log is generated, not recorded, so every reverse-engineering result can be scored against truth.dbc.
"""
import math
import random
import sys

random.seed(42)
DATA_ID = [0x5D, 0x12, 0xA7, 0x3C, 0xE1, 0x48, 0x9B, 0x06, 0x71, 0xC4, 0x2F, 0x88, 0xD3, 0x6A, 0xB5, 0x19]
GEARS = [(0, 0.0), (18, 105.0), (35, 62.0), (55, 43.0), (75, 33.0), (999, 26.0)]  # km/h limit, rpm per km/h


def crc8h2f(data):
    crc = 0xFF
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = ((crc << 1) ^ 0x2F) & 0xFF if crc & 0x80 else (crc << 1) & 0xFF
    return crc ^ 0xFF


def speed_at(t):
    """km/h: idle, two accelerations, cruise, braking, stop-and-go."""
    points = [(0, 0), (8, 0), (25, 52), (60, 55), (75, 20), (85, 0), (95, 0), (120, 88), (170, 92),
              (190, 40), (210, 45), (230, 0), (240, 0), (255, 35), (275, 30), (292, 0), (300, 0)]
    for (t0, v0), (t1, v1) in zip(points, points[1:]):
        if t0 <= t <= t1:
            x = (t - t0) / (t1 - t0)
            return v0 + (v1 - v0) * (1 - math.cos(math.pi * x)) / 2
    return 0.0


def rpm_at(speed):
    for limit, ratio in GEARS[1:]:
        if speed < limit:
            return max(780.0, speed * ratio + 650)
    return 780.0


def frame(t, can_id, data):
    return f"({t:.6f}) can0 {can_id:03X}#{bytes(data).hex().upper()}"


def build(seconds=300):
    lines, counter_esp, counter_ecm, coolant = [], 0, 0, 25.0
    obd_next, obd_pid = 0.0, 0x0D
    for step in range(seconds * 100):  # 10 ms ticks
        t = 1_700_000_000 + step / 100
        rel = step / 100
        speed = speed_at(rel)
        rpm = rpm_at(speed) + random.uniform(-15, 15)
        coolant = min(90.0, coolant + 0.004)
        if step % 2 == 0:  # 20 ms messages
            raw = round(speed * 100)
            body = [counter_esp, raw & 0xFF, raw >> 8, 0x00, 0x00, 0x40, 0x00]
            lines.append(frame(t, 0x1A0, [crc8h2f(body + [DATA_ID[counter_esp]])] + body))
            counter_esp = (counter_esp + 1) % 16
            wheels = []
            for offset in (0.3, -0.2, 0.1, -0.4):
                w = max(0, round((speed * (1 + offset / 100) + random.uniform(-0.05, 0.05)) * 100))
                wheels += [w & 0xFF, w >> 8]
            lines.append(frame(t + 0.0004, 0x1B0, wheels))
            raw_rpm = round(rpm / 0.25)
            throttle = round(min(100, max(0, 8 + 0.9 * (speed_at(rel + 1) - speed) * 10)) / 0.4)
            lines.append(frame(t + 0.0008, 0x2B0, [raw_rpm >> 8, raw_rpm & 0xFF, round(coolant + 40),
                                                   throttle, 0x00, 0x00, 0x00, counter_ecm]))
            counter_ecm = (counter_ecm + 1) % 16
        if step % 10 == 0:  # 100 ms message
            door = 1 if 87 <= rel <= 92 else 0
            brake = 1 if speed_at(rel + 0.5) < speed - 0.05 else 0
            lines.append(frame(t + 0.0012, 0x3C0, [door, brake, round((12.5 + 40) / 0.5), 0, 0, 0, 0, 0]))
        if rel >= obd_next:  # OBD-II poll: speed and RPM alternately, every 250 ms
            lines.append(frame(t + 0.0016, 0x7DF, [0x02, 0x01, obd_pid, 0, 0, 0, 0, 0]))
            if obd_pid == 0x0D:
                reply = [0x03, 0x41, 0x0D, round(speed), 0, 0, 0, 0]
            else:
                value = round(rpm * 4)
                reply = [0x04, 0x41, 0x0C, value >> 8, value & 0xFF, 0, 0, 0]
            lines.append(frame(t + 0.0216, 0x7E8, reply))
            obd_pid = 0x0C if obd_pid == 0x0D else 0x0D
            obd_next += 0.25
    lines.sort()
    return lines


if __name__ == "__main__":
    out = sys.argv[1] if len(sys.argv) > 1 else "synthetic.log"
    with open(out, "w") as f:
        f.write("\n".join(build()) + "\n")
    print(out)
