# Welcome to
# __________         __    __  .__                               __
# \______   \_____ _/  |__/  |_|  |   ____   ______ ____ _____  |  | __ ____
#  |    |  _/\__  \\   __\   __\  | _/ __ \ /  ___//    \\__  \ |  |/ // __ \
#  |    |   \ / __ \|  |  |  | |  |_\  ___/ \___ \|   |  \/ __ \|    <\  ___/
#  |________/(______/__|  |__| |____/\_____>______>___|__(______/__|__\\_____>
#
# This file can be a nice home for your Battlesnake logic and helper functions.
#
# To get you started we've included code to prevent your Battlesnake from moving backwards.
# For more info see docs.battlesnake.com

from server.Files import read_file, save_file
from config import SNAKE
import typing
import json, os

# info is called when you create your Battlesnake on play.battlesnake.com
# and controls your Battlesnake's appearance
# TIP: If you open your Battlesnake URL in a browser you should see this data
def info() -> typing.Dict:
    CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'snake-config.json')
    snake = read_file(CONFIG_PATH, json.load)
    if not snake:
        snake = {"apiversion":"1","author":"","color":"#888888","head":"default","tail":"default"}
        save_file(CONFIG_PATH, snake, callback=json.dump, indent=2, ensure_ascii=False)
        print("INFO", snake)
        return snake

    print("INFO Snake: ", snake)
    return snake

# start is called when your Battlesnake begins a game
def start(game_state: typing.Dict):
    SNAKE.clear_history()
    print("GAME START")

# end is called when your Battlesnake finishes a game
def end(game_state: typing.Dict):
    HISTORY_PATH = os.path.join(os.path.dirname(__file__), 'history')

    save_file(os.path.join(HISTORY_PATH, f"{SNAKE.__class__.__name__}-{game_state['game']['id']}.json"), SNAKE.get_history(), callback=json.dump, ensure_ascii=False)

    print("GAME OVER\n")

def move(game_state: typing.Dict) -> typing.Dict:
    next_move = SNAKE.choose_move(game_state)
    print(f"MOVE {game_state['turn']}: {next_move}")

    return {"move": next_move}

# Start server when `python main.py` is run
if __name__ == "__main__":
    from server.server import run_server
    run_server({"info": info, "start": start, "move": move, "end": end})
