from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, Event, GroupMessageEvent, PrivateMessageEvent

from .config import Config
from .room_store import RoomStore
from .points_service import PointsService
from .race_engine import RaceEngine
from .message_service import MessageService
from .models import Room, Horse, Bet, HorseState

config = Config()
room_store = RoomStore(config)
points_service = PointsService(config)
race_engine = RaceEngine(config)
message_service = MessageService(config)


def get_scope(event: Event) -> str:
    """Get room scope from event."""
    if isinstance(event, GroupMessageEvent):
        return f"group_{event.group_id}"
    elif isinstance(event, PrivateMessageEvent):
        return f"test_{event.user_id}"
    return ""


async def check_access(bot: Bot, event: Event) -> bool:
    """Check if user has access to horse racing."""
    if isinstance(event, PrivateMessageEvent):
        if not config.TEST_MODE:
            return False
        return event.user_id in config.TESTERS

    if isinstance(event, GroupMessageEvent):
        if config.TEST_MODE:
            return event.group_id in config.TEST_GROUPS
        return event.group_id in config.ALLOWED_GROUPS

    return False


register_cmd = on_command("赛马报名", priority=5)


@register_cmd.handle()
async def handle_register(bot: Bot, event: Event):
    """Handle horse registration."""
    if not await check_access(bot, event):
        await register_cmd.finish("无权限访问此功能")
        return

    scope = get_scope(event)
    lock = room_store.get_lock(scope)

    async with lock:
        room = room_store.get_room(scope)
        if not room:
            room = room_store.create_room(scope)

        if len(room.horses) >= 8:
            await register_cmd.finish("房间已满")
            return

        await register_cmd.finish("报名成功")


start_cmd = on_command("赛马开赛", priority=5)


@start_cmd.handle()
async def handle_start(bot: Bot, event: Event):
    """Handle race start."""
    if not await check_access(bot, event):
        await start_cmd.finish("无权限访问此功能")
        return

    scope = get_scope(event)
    lock = room_store.get_lock(scope)

    async with lock:
        room = room_store.get_room(scope)
        if not room:
            await start_cmd.finish("房间不存在")
            return

        if len(room.horses) < 2:
            await start_cmd.finish("至少需要2匹马才能开赛")
            return

        await race_engine.start_race(room)
        await start_cmd.finish("比赛开始！")


help_cmd = on_command("赛马帮助", priority=5)


@help_cmd.handle()
async def handle_help(bot: Bot, event: Event):
    """Handle help command."""
    help_text = """
赛马命令帮助：
/赛马报名 <马匹名> - 报名参赛
/赛马取消报名 - 取消报名
/赛马下注 <马匹名> <金额> - 下注
/赛马开赛 - 开始比赛
/赛马赔率 - 查看赔率
/赛马帮助 - 显示此帮助
    """
    await help_cmd.finish(help_text)
