# bot/bot_factory.py
import logging
from typing import Optional, Tuple
from telegram.constants import ParseMode
from telegram.ext import (
    Application,
    ApplicationBuilder,
    CommandHandler,
    MessageHandler,
    ChatMemberHandler,
    Defaults,
    filters,
)
from .models import TelegramBot, BotConfig
from .handlers import start, ping, echo, my_chat_member_update, error_handler
from .services import build_services

logger = logging.getLogger(__name__)

def _resolve_parse_mode(pm: Optional[str]):
    if not pm or pm == "None":
        return None
    return getattr(ParseMode, pm, ParseMode.HTML)

def build_application_for_bot(tb: TelegramBot) -> Tuple[Application, Optional[list]]:
    cfg = BotConfig.objects.filter(bot=tb).first()
    if not cfg:
        raise RuntimeError(f"BotConfig не найден для бота '{tb}'")

    parse_mode = _resolve_parse_mode(cfg.parse_mode)
    defaults = Defaults(parse_mode=parse_mode) if parse_mode else None
    allowed_updates = cfg.allowed_updates or None

    builder: ApplicationBuilder = Application.builder().token(tb.token)
    if defaults:
        builder = builder.defaults(defaults)

    app = builder.build()

    # зарегистрировать хендлеры
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("ping", ping))
    app.add_handler(ChatMemberHandler(my_chat_member_update, ChatMemberHandler.MY_CHAT_MEMBER))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
    app.add_error_handler(error_handler)

    # инжект зависимостей для КОНКРЕТНОГО бота
    services = build_services(tb)
    app.bot_data["services"] = services
    app.bot_data["allowed_updates"] = allowed_updates

    logger.info(
        "Built app for bot=%s (@%s), parse_mode=%s, allowed_updates=%s",
        tb.name, tb.username or "—", parse_mode, allowed_updates
    )
    return app, allowed_updates
