from telegram import Update
from telegram.ext import ContextTypes

from bot.core.logger import logger
from bot.services.steam import parse_steam_id


async def add_player(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if not context.args:
        await update.message.reply_text("Usage: /addplayer <steam_id> [name]")
        return

    try:
        steam32 = parse_steam_id(context.args[0])
    except ValueError as e:
        await update.message.reply_text(str(e))
        return

    name = " ".join(context.args[1:]) if len(context.args) > 1 else f"Player_{steam32}"
    chat_id = update.effective_chat.id
    store = context.bot_data["store"]

    if store.add_player(chat_id, steam32, name):
        await update.message.reply_text(f"Added {name} (Steam32: {steam32})")
        logger.info("Added player steam32=%s name=%r to chat_id=%s", steam32, name, chat_id)
    else:
        await update.message.reply_text(f"{name} (Steam32: {steam32}) is already tracked.")


async def remove_player(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if not context.args:
        await update.message.reply_text("Usage: /removeplayer <steam_id>")
        return

    try:
        steam32 = parse_steam_id(context.args[0])
    except ValueError as e:
        await update.message.reply_text(str(e))
        return

    chat_id = update.effective_chat.id
    store = context.bot_data["store"]

    if store.remove_player(chat_id, steam32):
        await update.message.reply_text(f"Removed Steam32: {steam32}")
        logger.info("Removed player steam32=%s from chat_id=%s", steam32, chat_id)
    else:
        await update.message.reply_text(f"Player with Steam32 {steam32} is not tracked.")


async def list_players(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = update.effective_chat.id
    store = context.bot_data["store"]
    players = store.list_players(chat_id)

    if not players:
        await update.message.reply_text("No players tracked yet. Use /addplayer <steam_id> [name]")
        return

    lines = [f"Tracked players ({len(players)}):"]
    for i, p in enumerate(players, 1):
        lines.append(f"{i}. {p.name} — Steam32: {p.steam32}")
    await update.message.reply_text("\n".join(lines))
