#!/usr/bin/env python3
import argparse
import time
from client import get_state, send_turn, logger, TIME_BEFORE_RETRY


parser = argparse.ArgumentParser()
parser.add_argument("--server", type=str, default="http://localhost:5000", help="Server address.")
parser.add_argument("--game", type=str, default="main", help="'main' or 'test_#'.")
parser.add_argument("--token", type=str, default=None, help="API token.")
parser.add_argument("--log_level", type=str, default="WARNING", choices=["ERROR", "WARNING", "INFO"])
# you can add your own arguments, the strategy function will get them


def strategy(team_id: int, state: dict, args: argparse.Namespace) -> dict:
    """Finds the best move for the given state.

    This function is called every round.
    It should return a dict with actions for each of team's soldiers.

    State format:
    ```yaml
    {
        map: [[{
            home_for_team: Optional[int],
            occupied_by_team: Optional[int],
            hill: bool,
            members: [{
                type: "soldier",
                team: int,
                id: int,
                remaining_rounds: int
            }]
        }]]
    }
    ```

    Turn format:
    ```yaml
    {
        members: [{
            id: int,
            action: Optional[str]
            # None, "left", "right", "up", "down"
        }]
    }
    ```
    """
    return {}


def main(args: argparse.Namespace):
    min_round = 0
    logger.setLevel(args.log_level)

    while True:
        state, wait_time = get_state(min_round)
        if state is None:
            # retry later
            time.sleep(wait_time)
            continue

        turn = strategy(state["team_id"], state["state"], args)

        round = state["round"]
        while not send_turn(turn, round):
            # if there was a connection error, retry later
            time.sleep(TIME_BEFORE_RETRY)
        min_round = round + 1


if __name__ == '__main__':
    args = parser.parse_args()
    main(args)