import asyncio
import math
import sys

from websockets.asyncio.client import connect


async def hello(id, seed):
    print(f"ID:*{id}*")
    uri = "ws://ai-challenger.net:5555/steer/client?ID=" + id + "&ARG0=" + seed
    async with connect(uri) as websocket:
        cur_x = 0
        cur_y = 0
        next_x = 0
        next_y = 0
        cur_angle = 0
        while True:
            response = await websocket.recv()
            lines = response.split("\n")
            print(f"Received: {response}")
            for line in lines:
                if line.startswith("pos:"):
                    line = line.removeprefix("pos:")
                    cur_x = float(line.split(",")[0])
                    cur_y = float(line.split(",")[1])
                if line.startswith("target_pos:"):
                    line = line.removeprefix("target_pos:")
                    next_x = float(line.split(",")[0])
                    next_y = float(line.split(",")[1])
                if line.startswith("Angle:"):
                    line = line.removeprefix("Angle:")
                    cur_angle = float(line)
            x_off = next_x - cur_x
            y_off = next_y - cur_y
            angle = (math.atan2(y_off, x_off) / math.pi) * 180.0 + 90

            # Add your own logig here
            # Sample logic
            if cur_angle - angle > 0:
                await websocket.send("j")
            else:
                await websocket.send("l")


id = sys.argv[1]
seed = sys.argv[2]

asyncio.run(hello(id, seed))
