import logging
from telegram import Update
from telegram.ext import ContextTypes

logger = logging.getLogger(__name__)

def _svc(context: ContextTypes.DEFAULT_TYPE):
    return context.application.bot_data["services"]  # BotServices

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if update.effective_chat:
        s = _svc(context)
        await s.chats.upsert_chat(
            bot=s.bot,
            chat_id=update.effective_chat.id,
            chat_type=update.effective_chat.type,
            title=getattr(update.effective_chat, "title", "") or "",
            username=getattr(update.effective_chat, "username", "") or "",
            is_member=True,
            touch_last_message=True,
        )
    user = update.effective_user
    await update.effective_message.reply_text(f"Привет, {user.first_name or 'друг'}! Я бот автопостинга.")

async def ping(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.effective_message.reply_text("pong")

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if update.effective_chat:
        s = _svc(context)
        await s.chats.upsert_chat(
            bot=s.bot,
            chat_id=update.effective_chat.id,
            chat_type=update.effective_chat.type,
            title=getattr(update.effective_chat, "title", "") or "",
            username=getattr(update.effective_chat, "username", "") or "",
            is_member=True,
            touch_last_message=True,
        )
    await update.effective_message.reply_text(update.effective_message.text)

async def my_chat_member_update(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    try:
        chat = update.effective_chat
        status = update.my_chat_member.new_chat_member.status  # administrator|member|left|kicked
        is_member = status in ("administrator", "member")
        s = _svc(context)
        await s.chats.upsert_chat(
            bot=s.bot,
            chat_id=chat.id,
            chat_type=chat.type,
            title=getattr(chat, "title", "") or "",
            username=getattr(chat, "username", "") or "",
            is_member=is_member,
        )
        logger.info("my_chat_member: %s in %s (%s)", status, chat.id, chat.type)
    except Exception:
        logger.exception("Failed to process my_chat_member update")

async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
    logger.exception("PTB error: %s", context.error)