# Step 2: cut the drive into 5-second windows.
# The network never sees one second alone. It looks at 5 seconds and turns
# them into 4 numbers, plus the answer it should learn.

WINDOW = 5

rows = []
with open("drive.csv") as f:
    next(f)  # skip the header
    for line in f:
        t, speed, rpm, throttle, action = line.strip().split(",")
        rows.append((float(speed), float(rpm), float(throttle), action))

out = open("windows.csv", "w")
out.write("speed,change,rpm,throttle,action\n")
count = 0
for start in range(len(rows) - WINDOW + 1):
    w = rows[start:start + WINDOW]
    speed = sum(r[0] for r in w) / WINDOW / 100      # average speed, about 0 to 1
    change = (w[-1][0] - w[0][0]) / 40               # did the car speed up or slow down?
    rpm = sum(r[1] for r in w) / WINDOW / 5000       # average engine speed
    throttle = sum(r[2] for r in w) / WINDOW / 100   # average pedal press
    action = w[-1][3]                                # the answer: what the driver does now
    out.write(f"{speed:.4f},{change:.4f},{rpm:.4f},{throttle:.4f},{action}\n")
    count += 1
out.close()

print(f"Read {len(rows)} seconds of driving.")
print(f"Wrote {count} windows of {WINDOW} seconds to windows.csv")
print("Each window is 4 numbers: speed, change, rpm, throttle. Then the answer.")
