import argparse
import logging
import os
import sys
from typing import Any

from .entrypoints import Entrypoints
from .level import Level
from .menu import Action
from .mob import BaseMob, load_character

logger = logging.getLogger(__name__)

# FIXME replace this global declaration
UI: Any = None


def play_room(room: list[BaseMob], level: Level) -> int:
    if room is None:
        logger.info('Empty room')
        UI.empty_room()
        return 1

    for mob in room:
        logger.info('Meet mob %s', mob.name)
        UI.meet_mob(mob)
        match UI.action_menu([Action.COMBAT, Action.FUIR]):
            case Action.COMBAT:
                pvs = level.combat(mob, level.player)
                UI.fight_pvs(level.player, mob, pvs)
                if level.player.current_pv <= 0:
                    UI.player_dead()
                    sys.exit(0)
                if mob.current_pv == 0:
                    UI.mob_dead(mob)
            case Action.FUIR:
                UI.run_away()
                return 0

    return 1


def play_donjon(level: Level) -> None:
    while level.exit_level:
        UI.entering_room(level.current_room_index)
        match UI.action_menu([Action.PIECE_SUIVANTE, Action.QUITTER]):
            case Action.PIECE_SUIVANTE:
                if level.current_room_index >= len(level.rooms):
                    logger.info('Exiting last room')
                    UI.last_room()
                    break
                logger.info('Entering next room')
                level.current_room_index += play_room(level.rooms[level.current_room_index], level)
                level.player.current_pv = level.player.max_pv
            case Action.QUITTER:
                level.exit_level = False
                logger.info('Leaving game')
                UI.leave(level.player)


def app() -> None:
    entrypoints = Entrypoints()

    parser = argparse.ArgumentParser(
        prog='elironwars',
        description='elironwars CLI',
    )
    parser.add_argument('--player', default='Jamin')
    parser.add_argument('--ui', default='console', choices=entrypoints.ui.names)
    parser.add_argument('--log-level', default='ERROR', choices=logging.getLevelNamesMapping().keys())
    args = parser.parse_args()

    os.makedirs('logs', exist_ok=True)
    logging.basicConfig(filename='logs/app.log', level=logging.getLevelName(args.log_level))
    logging.info('start')

    loaded_character = load_character(args.player)
    if not loaded_character:
        sys.exit(-1)

    global UI
    UI = entrypoints.load_ui(args.ui)
    UI.select_player(loaded_character)

    # Créer des instances de BaseMob
    yanaar = BaseMob("Yanaar", 15, 2, 1, 3, 2)
    ulnarain = BaseMob("Ulnarain", 20, 3, 3, 2, 2)
    skroll = BaseMob("Skroll", 25, 5, 3, 1, 2)

    # Liste d'instances de BaseMob (au lieu d'un ensemble pour autoriser des doublons)
    mobs_list = [yanaar, skroll, ulnarain]

    level = Level(2, loaded_character, mobs_list)
    UI.entering_donjon(level)

    play_donjon(level)


# Exemple d'utilisation
if __name__ == "__main__":
    app()
