#!/usr/bin/env python3
"""Dye bot scaffold.

A minimal, working bot to start from. It connects, uploads one unit program,
and spawns units on the edge of its territory whenever it can afford them.
Replace PROGRAM (what your units do) and decide() (where, when and how much to
spawn); the plumbing below can stay as it is.

    pip install websockets
    python dye_bot.py ws://HOST:9091

Your player name comes from $PLAYER, which the tournament runner sets in your
container ("player/bot"). On a local demo server (dyedemo with an "open"
slot) run it as: PLAYER=open python dye_bot.py ws://127.0.0.1:9091

Full reference: https://hyxor.com/dye/readme
"""

import asyncio
import json
import os
import random
import sys

import websockets

# --- your units -------------------------------------------------------------

# Unit program for upload slot 0: claim neutral ground first, steer around
# units and walls, otherwise go straight with occasional turns.
PROGRAM = """
loop:   SENSE A, 1        ; A = ahead, B = right, C = left
        SENSE B, 2
        SENSE C, 4
        CMP   A, 0
        JZ    go          ; neutral ahead: take it
        CMP   B, 0
        JZ    right
        CMP   C, 0
        JZ    left
        CMP   A, 3
        JZ    right       ; wall ahead
        RND   D
        CMP   D, 8192     ; otherwise turn ~1/8 of the time
        JLT   right
go:     LOOK  D, 1
        CMP   D, 0
        JNZ   right       ; a unit is in the way
        STEP
        JMP   loop
right:  TURN  R
        JMP   go
left:   TURN  L
        JMP   go
"""

ENERGY = 60  # energy loaded into each unit
DECIDE_EVERY = 0.25  # seconds between decisions (the game runs 40 ticks/sec)
MAX_SPAWNS_PER_DECISION = 8

# --- your strategy -----------------------------------------------------------


def decide(frame, me, fee):
    """Return a list of commands to send, given the newest state frame.

    frame: the parsed state frame (see the README, "the state frame").
    me:    this bot's entry from frame["players"].
    fee:   spawn fee for slot 0 (from the server's OK UPLOAD reply).
    """
    budget = me["reserve"]
    cost = fee + ENERGY
    if budget < cost:
        return []

    occupied = {(u["x"], u["y"]) for u in frame["units"]}
    edge = border_tiles(frame, me["pid"], occupied)
    random.shuffle(edge)

    commands = []
    for x, y in edge[:MAX_SPAWNS_PER_DECISION]:
        if budget < cost:
            break
        commands.append(f"SPAWN 0 {x} {y} {ENERGY}")
        budget -= cost
    return commands


def border_tiles(frame, pid, occupied):
    """Our free tiles that touch neutral ground (where a new unit is useful).

    Scans only our own tiles (str.find per row), so it stays cheap in Python
    even on a 512x512 board.
    """
    paint = frame["paint"]
    w, h = frame["width"], frame["height"]
    mine = format(pid, "x")
    tiles = []
    for y, row in enumerate(paint):
        x = row.find(mine)
        while x != -1:
            if (x, y) not in occupied:
                for nx, ny in ((x, y - 1), (x + 1, y), (x, y + 1), (x - 1, y)):
                    if 0 <= nx < w and 0 <= ny < h and paint[ny][nx] == "0":
                        tiles.append((x, y))
                        break
            x = row.find(mine, x + 1)
    return tiles


# --- plumbing ------------------------------------------------------------------


class State:
    def __init__(self):
        # our player name: set by the tournament runner ("player/bot");
        # local demo open slots are named "open", "open-2", ...
        self.name = os.environ.get("PLAYER", "open")
        self.fee = None  # from "OK UPLOAD 0 len=.. fee=.."
        self.latest = None  # newest raw state frame (parsed only when needed)
        self.done = False


def on_reply(state, line):
    """Handle a one-line reply to one of our commands: OK ... / ERR ..."""
    if line.startswith("OK UPLOAD"):
        state.fee = int(line.split("fee=")[1])
        print(line)
    elif line.startswith("ERR"):
        print(line)  # e.g. a rejected SPAWN; nothing was charged


async def reader(ws, state):
    """Receive everything; keep only the newest state frame."""
    async for msg in ws:
        if msg.startswith("{"):
            if msg.startswith('{"type":"result"'):
                result = json.loads(msg)
                print("match over:", [(p["name"], p["score"]) for p in result["placements"]])
                state.done = True
                return
            state.latest = msg
        else:
            on_reply(state, msg)


async def decider(ws, state):
    last_tick = -1
    next_status = 0
    while not state.done:
        await asyncio.sleep(DECIDE_EVERY)
        if state.latest is None or state.fee is None:
            continue
        frame = json.loads(state.latest)
        # commands apply next tick: wait for a fresh frame before deciding again
        if frame["tick"] <= last_tick + 1:
            continue
        last_tick = frame["tick"]
        me = next((p for p in frame["players"] if p["name"] == state.name), None)
        if me is None or me["eliminated"]:
            continue
        if frame["tick"] >= next_status:  # a status line every ~10 seconds
            print(f"tick {frame['tick']}/{frame['match_ticks']}: {me['tiles']} tiles, "
                  f"{me['units']} units, reserve {me['reserve']}, score {me['score']}")
            next_status = frame["tick"] + 200
        for cmd in decide(frame, me, state.fee):
            await ws.send(cmd)


async def main(url):
    state = State()
    print(f"playing as {state.name}")
    try:
        async with websockets.connect(url, max_size=None) as ws:
            await ws.send("UPLOAD 0\n" + PROGRAM)
            await asyncio.gather(reader(ws, state), decider(ws, state))
    except websockets.ConnectionClosed:
        print("connection closed by the server")


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else "ws://127.0.0.1:9091"))
