import asyncio import html import logging from datetime import datetime, timedelta from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, BotCommand from telegram.ext import ( Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters, ContextTypes, ConversationHandler, TypeHandler ) from config import ( TELEGRAM_BOT_TOKEN, PERIOD_OPTIONS, POLL_INTERVAL, POLL_TIMEOUT, DROP_PENDING_UPDATES, ALLOWED_UPDATES, LOG_LEVEL ) from version import BOT_VERSION from database import Database from lichess_api import LichessAPI from formatters import StatsFormatter from i18n import t, format_period, format_count, LANGUAGES from message_counters import MessageCounters from notifications import AdminNotifier from onboarding import link_player, normalise_username, start_returning_text, BOT_COMMANDS from periodic import PeriodicMonitor from events import event import time # Longest text we put into one Telegram message (the hard limit is 4096); # longer screens (/getgamers, /today with many players) are split. MAX_MESSAGE_CHARS = 4000 # Pause between the direct lichess.org rating requests of /getgamers and /delgamer RATINGS_REQUEST_PAUSE = 0.5 # Configure logging (level from LOG_LEVEL env, INFO by default) logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=getattr(logging, LOG_LEVEL, logging.INFO) ) # httpx logs every Telegram API call at INFO with the full URL, i.e. the bot # token in plain text, one line per getUpdates every 30s. Keep only its warnings. logging.getLogger("httpx").setLevel(logging.WARNING) logger = logging.getLogger(__name__) # Conversation state of /addtoken (the only conversation left: a name is plain text) WAITING_FOR_TOKEN = 0 class LichessBot: def __init__(self): self.db = Database() self.lichess_api = LichessAPI() self.counters = MessageCounters() # Message counters self.notifier = AdminNotifier(self.db) self.monitor = PeriodicMonitor(self.db, self.lichess_api, self.counters, self.notifier) self.application = None # Will be set when application is created async def test_admin_notify(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Manual test to verify admin notifications delivery path. Admin-only: anyone else gets no reply.""" user = update.effective_user admin_chat_id = self.db.get_admin_chat_id() if admin_chat_id is None or update.effective_chat is None or update.effective_chat.id != admin_chat_id: return try: await self.notifier.notify_new_player("test_player_notify", user.id, user.username if user else None) await update.message.reply_text("✅ Admin notification test triggered.") except Exception as e: logger.error(f"test_admin_notify failed: {e}") await update.message.reply_text(f"❌ Failed to trigger admin notification: {e}") def _status_mark(self, gamer_id: int) -> str: """ '⛔' for a player whose Lichess account the last bulk status refresh saw as closed, '❓' for one Lichess no longer knows (deleted or renamed, see player_status.py), else ''. /delgamer prefixes the name with it. """ status = self.db.get_gamer_status(gamer_id) if not status: return "" if status.get('disabled'): return "⛔" if status.get('not_found'): return "❓" return "" @staticmethod def player_state(status, now_ts: float, lang: str): """ The state line of a player on the /getgamers screen, from the bulk status alone (docs/design/product_concepts.md 2.1 wording), as (icon, text, sort_key): 🟢 played today (seen_at < 24 h) / yesterday (< 48 h), ⚪ "N days quiet" (< 30), 💤 "N days quiet" (30-89) / "3+ months quiet" (90+), ⛔ account closed, ❓ not found on Lichess, ⚪ "not checked yet" (no status row or no seen_at). sort_key orders 🟢 → ⚪ by days → 💤 → ⛔/❓, as the screen lists them. """ if status and status.get('disabled'): return '⛔', t('status_closed', lang), (3, 0) if status and status.get('not_found'): return '❓', t('status_not_found', lang), (3, 1) seen_at = status.get('seen_at') if status else None if seen_at is None: return '⚪', t('status_unchecked', lang), (1, 10 ** 9) age = now_ts - seen_at / 1000 if age < 86400: return '🟢', t('status_played_today', lang), (0, 0) if age < 2 * 86400: return '🟢', t('status_played_yesterday', lang), (0, 1) days = int(age // 86400) quiet = t('status_quiet', lang, days=format_count(days, 'days', lang)) if days < 30: return '⚪', quiet, (1, days) if days < 90: return '💤', quiet, (2, days) return '💤', t('status_quiet_months', lang), (2, days) @staticmethod def _split_messages(head, blocks, tail=None, sep="\n", limit=MAX_MESSAGE_CHARS): """ [head, blocks joined by `sep`, tail] as one text ("\\n\\n" around head and tail), cut at block boundaries into pieces of at most `limit` characters: /getgamers with dozens of players, /today with many players. Always at least one piece. """ pieces = [] current = head or "" first = True for block in blocks: glue = "\n\n" if first and current else sep if current and len(current) + len(glue) + len(block) > limit: pieces.append(current) current = block else: current = current + glue + block if current else block first = False if tail: if current and len(current) + 2 + len(tail) > limit: pieces.append(current) current = tail else: current = current + "\n\n" + tail if current else tail pieces.append(current) return pieces def _gamers_state_messages(self, gamers, lang: str, table: str = None): """ The /getgamers screen (product_concepts.md 2.1 / proposal 4.1.2): a header with the count, one "icon name / state · period" entry per player (sorted by state, then name), optionally the ratings
 table, then the "another player — send a name" footer. Split
        into several texts when too long (_split_messages). The period is not
        shown for closed / not-found players.
        """
        statuses = self.db.get_gamer_statuses([g['id'] for g in gamers])
        now = time.time()
        entries = []
        for g in gamers:
            icon, text, key = self.player_state(statuses.get(g['id']), now, lang)
            period = ""
            if icon not in ('⛔', '❓'):
                period = " · " + format_period(g.get('period_minutes') or 0, lang)
            entries.append((key, g['username'].lower(),
                            t('gamer_line', lang, icon=icon, name=html.escape(g['username']), status=text, period=period)))
        entries.sort(key=lambda e: (e[0], e[1]))
        blocks = [line for _, _, line in entries]
        if table:
            blocks.append("\n
" + table + "
") return self._split_messages(t('gamers_header', lang, n=len(gamers)), blocks, t('gamers_footer', lang)) async def _fetch_ratings(self, gamers): """ Bullet/blitz/rapid ratings of `gamers` straight from lichess.org (get_user_ratings), RATINGS_REQUEST_PAUSE between players; a missing rating or a failed request gives None (shown as "—"). Items for StatsFormatter.format_gamers_table. """ gamers_data = [] for i, gamer in enumerate(gamers): username = gamer['username'] ratings = {'bullet': None, 'blitz': None, 'rapid': None} try: logger.debug(f"Requesting ratings for {username}") ratings_data = await self.lichess_api.get_user_ratings(username) if ratings_data and 'perfs' in ratings_data: perfs = ratings_data['perfs'] for mode in ratings: ratings[mode] = (perfs.get(mode) or {}).get('rating') except Exception as e: logger.error(f"Error getting ratings for {username}: {e}") gamers_data.append({'id': gamer['id'], 'username': username, **ratings}) # Add delay between requests to avoid rate limiting if i < len(gamers) - 1: # Don't sleep after the last one await asyncio.sleep(RATINGS_REQUEST_PAUSE) return gamers_data def get_user_language_from_update(self, update: Update) -> str: """Get user's selected bot language from database""" user = update.effective_user if user: # Update user info in database (this will auto-detect language for new users) self.db.add_or_get_telegram_user( user_id=user.id, username=user.username, first_name=user.first_name, last_name=user.last_name, language_code=user.language_code ) # Get user's selected bot language from database return self.db.get_user_language(user.id) return 'en' # ---- Onboarding (docs/design/onboarding.md) ------------------------------ # Every reply below goes through _reply: parse_mode='HTML' (names in ), # link previews off — the only link is the profile in player_added, and the # literal "lichess.org/@/…" on the first screen must not grow a preview card. # There is no flow state: any plain text in a private chat is a player name. async def _reply(self, update: Update, text: str, reply_markup=None): return await update.message.reply_text( text, parse_mode='HTML', disable_web_page_preview=True, reply_markup=reply_markup ) def _where_name_keyboard(self, lang: str) -> InlineKeyboardMarkup: """One button: the "where is the username" picture (callback addgamer_how).""" return InlineKeyboardMarkup([[ InlineKeyboardButton(t('btn_where_name', lang), callback_data="addgamer_how") ]]) @staticmethod def _start_other_languages(lang: str): """ Language buttons of the new-user /start screen: ru gets English, en gets Русский, everyone else (uz/tr/fa/ar) both — many of them read Russian better than English. Going back to uz/tr/fa/ar is via /lang. """ if lang == 'ru': return ['en'] if lang == 'en': return ['ru'] return ['ru', 'en'] def _start_keyboard(self, lang: str) -> InlineKeyboardMarkup: """New-user /start: [where is the username] / [the other language(s)].""" return InlineKeyboardMarkup([ [InlineKeyboardButton(t('btn_where_name', lang), callback_data="addgamer_how")], [InlineKeyboardButton(t(f'btn_lang_{other}', lang), callback_data=f"start_lang_{other}") for other in self._start_other_languages(lang)], ]) def _callback_lang(self, update: Update) -> str: """Language for a callback query: refresh the user row (as every handler does), then read bot_language.""" user = update.effective_user self.db.add_or_get_telegram_user( user_id=user.id, username=user.username, first_name=user.first_name, last_name=user.last_name, language_code=user.language_code ) return self.db.get_user_language(user.id) async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """ /start — one message. A user who already follows players gets the summary with the three commands (spec 2b); anyone else (new, or everyone deleted) gets the new-user screen (2a) with [where is the username] / [other language] buttons and is simply expected to type a name. """ user = update.effective_user logger.info(f"📝 start() method called for user {user.id}") event('cmd', uid=user.id, name='start') lang_code = user.language_code logger.info(f"User info: id={user.id}, username={user.username}, lang_code={lang_code}") is_new_user = self.db.add_or_get_telegram_user( user_id=user.id, username=user.username, first_name=user.first_name, last_name=user.last_name, language_code=lang_code ) lang = self.db.get_user_language(user.id) gamers = self.db.get_user_gamers(user.id) screen = 'returning' if gamers else 'new' event('user_start', uid=user.id, new=is_new_user, lang=lang, tg_lang=lang_code, screen=screen) # Notify admin bot about new user if is_new_user: try: await self.notifier.notify_new_user( user_id=user.id, username=user.username, first_name=user.first_name ) except Exception as e: logger.error(f"Failed to notify admin about new user: {e}") import traceback logger.error(traceback.format_exc()) if gamers: await self._reply(update, start_returning_text([g['username'] for g in gamers], lang)) else: await self._reply(update, t('start_new', lang), reply_markup=self._start_keyboard(lang)) self.counters.increment('start') async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Help command handler""" event('cmd', uid=update.effective_user.id, name='help') lang = self.get_user_language_from_update(update) await self._reply(update, t('help_message', lang)) async def addgamer_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """/addgamer: ask for the name right away (spec 2a′), one button for the picture.""" user_id = update.effective_user.id event('cmd', uid=user_id, name='addgamer') logger.info(f"addgamer prompt for user {user_id}") lang = self.get_user_language_from_update(update) await self._reply(update, t('add_prompt', lang), reply_markup=self._where_name_keyboard(lang)) self.counters.increment('addgamer') async def handle_start_lang(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """ 🇬🇧 / 🇷🇺 on the new-user /start screen: save the language and redraw the same message in it, with the buttons of the new language (_start_keyboard; the callback accepts every code of LANGUAGES). No separate "language set" message — the user sees the result. Stateless, so it works after a restart. """ query = update.callback_query await query.answer() user = query.from_user selected = query.data.rsplit('_', 1)[1] # one of LANGUAGES self._callback_lang(update) # keeps the user row fresh if not self.db.set_user_language(user.id, selected): logger.warning(f"start_lang: unsupported language {selected!r} from user {user.id}") return event('lang_set', uid=user.id, lang=selected, via='start') try: await query.edit_message_text( t('start_new', selected), parse_mode='HTML', disable_web_page_preview=True, reply_markup=self._start_keyboard(selected) ) except Exception as e: # Typically "Message is not modified": the screen was already in that # language (the user changed it via /lang in between). Nothing to do. logger.info(f"start_lang: could not redraw the start screen for user {user.id}: {e}") async def addgamer_show_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Callback addgamer_how: replace the message with the "where is the username" text (no picture).""" query = update.callback_query if not query or not query.message: logger.error("addgamer_show_help: Invalid query or message") return await query.answer() lang = self._callback_lang(update) logger.info(f"addgamer_show_help called for user {query.from_user.id}") await query.edit_message_text(t('where_name_text', lang), parse_mode='HTML', disable_web_page_preview=True) async def addtoken_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Start addtoken command - token required""" event('cmd', uid=update.effective_user.id, name='addtoken') lang = self.get_user_language_from_update(update) await update.message.reply_text(t('addtoken_prompt', lang)) self.counters.increment('addtoken') return WAITING_FOR_TOKEN async def addtoken_cancel(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """/cancel inside the /addtoken conversation: just end it.""" event('cmd', uid=update.effective_user.id, name='cancel') return ConversationHandler.END async def addtoken_leave(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """ Any other command typed inside the /addtoken conversation (/start, /addgamer, /help, /today...) ends it and runs that command. Without this the bot itself asked for a player name (/start, /addgamer) and then rejected the name as "not a token" until the user found /cancel. """ text = update.message.text or '' name = text.split()[0][1:].split('@')[0].lower() if text.startswith('/') else '' callback = self._command_callbacks.get(name, self.handle_unknown_command) await callback(update, context) return ConversationHandler.END async def cancel_nothing(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """/cancel outside any conversation: the addtoken texts advertise it, so answer instead of 'no such command'.""" event('cmd', uid=update.effective_user.id, name='cancel') lang = self.get_user_language_from_update(update) await self._reply(update, t('cancel_nothing', lang)) async def handle_token(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle token input for /addtoken""" token = update.message.text.strip() user_id = update.effective_user.id if not token.startswith('lip_'): # The "/addtoken trap" from the funnel analysis: people who typed # /addtoken by mistake sent a player name here and got "invalid token" # for every further message. Lichess personal API tokens always start # with "lip_"; anything else gets the explanation and the way out # (/cancel, then just the name) instead of a request to Lichess. logger.info(f"addtoken: text from user {user_id} does not look like a token: {token[:40]!r}") event('addtoken_result', uid=user_id, result='not_a_token') lang = self.get_user_language_from_update(update) await self._reply(update, t('addtoken_not_token', lang)) return WAITING_FOR_TOKEN logger.info(f"Processing token for user {user_id}, token prefix: {token[:10]}...") # Get username from token profile = await self.lichess_api.get_user_profile(token) logger.info(f"Profile response: {profile is not None}") if profile: username = profile.get('username') if username: # Check if this gamer is already tracked by this user user_gamers = self.db.get_user_gamers(user_id) existing_gamer = next((g for g in user_gamers if g['username'].lower() == username.lower()), None) lang = self.get_user_language_from_update(update) if existing_gamer: # Update token for existing gamer self.db.add_user_gamer(user_id, existing_gamer['id'], token) event('addtoken_result', uid=user_id, result='token_updated', canonical=username) await update.message.reply_text( t('token_added', lang, username=username) ) # Always notify admin about link/added player try: user_obj = update.effective_user await self.notifier.notify_new_player(username, user_id, user_obj.username if user_obj else None) except Exception as e: logger.error(f"Admin notify failed after token update: {e}") else: # Add new gamer and link with token (shared with /addgamer, see onboarding.py) result = await link_player(self, user_id, update.effective_user, username, token, via='addtoken') if not result.added: # Pair appeared between the check above and the insert; the token is stored event('addtoken_result', uid=user_id, result='token_updated', canonical=username) await update.message.reply_text( t('token_added', lang, username=username) ) else: event('addtoken_result', uid=user_id, result='added', canonical=username) await update.message.reply_text( t('gamer_added_with_token', lang, username=username) ) return ConversationHandler.END else: event('addtoken_result', uid=user_id, result='no_username') lang = self.get_user_language_from_update(update) await update.message.reply_text( t('token_username_error', lang) ) return WAITING_FOR_TOKEN else: event('addtoken_result', uid=user_id, result='invalid_token') lang = self.get_user_language_from_update(update) await update.message.reply_text( t('invalid_token', lang) ) return WAITING_FOR_TOKEN async def handle_username(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """ Any plain text in a private chat (outside the /addtoken conversation) is a player name (spec rule 3.6): normalise it (profile URL, @name, "add Name" -> Name), then chess.com -> hint, not a name -> format hint, otherwise check on Lichess -> added / not found / closed / already / unavailable. No flow state, so "another player? just send a name" holds at any moment. Every echoed name is HTML-escaped: the user's text goes back into HTML. """ user_id = update.effective_user.id raw = update.message.text or '' username, kind = normalise_username(raw) event('addgamer_input', uid=user_id, text=raw.strip(), normalised=username, kind=kind) lang = self.get_user_language_from_update(update) shown = html.escape(username) if kind == 'chesscom': logger.info(f"addgamer: user {user_id} sent a chess.com name/link: {raw[:60]!r}") event('addgamer_result', uid=user_id, username=username, result='chesscom') await self._reply(update, t('chesscom_hint', lang)) return if kind == 'format': logger.info(f"addgamer: text from user {user_id} does not look like a username: {raw[:60]!r}") event('addgamer_result', uid=user_id, username=username, result='format') await self._reply(update, t('name_format_hint', lang), reply_markup=self._where_name_keyboard(lang)) return # Check if user exists on Lichess logger.info(f"addgamer: user {user_id} entered username {username!r} (kind={kind})") lichess_user = await self.lichess_api.check_user_exists(username) if lichess_user is None: # Transient API failure (rate limit, network error, unexpected status) — # don't tell the user the name is wrong, it may well be valid. event('addgamer_result', uid=user_id, username=username, result='lichess_error') await self._reply(update, t('lichess_unavailable', lang)) return if not lichess_user: logger.info(f"addgamer: username {username!r} not found on Lichess (user {user_id})") event('addgamer_result', uid=user_id, username=username, result='not_found') await self._reply(update, t('player_not_found', lang, username=shown), reply_markup=self._where_name_keyboard(lang)) return if lichess_user.get('disabled'): # Lichess answers 200 for closed accounts too; they never have new games, # tracking one is just a wasted request every period. logger.info(f"addgamer: username {username!r} is a closed Lichess account (user {user_id})") event('addgamer_result', uid=user_id, username=username, result='closed') await self._reply(update, t('player_closed', lang, username=shown)) return # Store the canonical spelling Lichess uses, not whatever case the user typed typed_username = username username = lichess_user['username'] shown = html.escape(username) # Check if this gamer is already tracked by this user user_gamers = self.db.get_user_gamers(user_id) existing_gamer = next((g for g in user_gamers if g['username'].lower() == username.lower()), None) if existing_gamer: # Player is already being tracked by this user event('addgamer_result', uid=user_id, username=typed_username, result='already', canonical=username) await self._reply(update, t('player_already', lang, username=shown)) return # Add gamer to database (without token) and link it to this user # (shared with /addtoken, see onboarding.py) result = await link_player(self, user_id, update.effective_user, username, None, via='addgamer') # If add_user_gamer returned False, it means the pair already exists (shouldn't happen after our check, but just in case) if not result.added: event('addgamer_result', uid=user_id, username=typed_username, result='already', canonical=username) await self._reply(update, t('player_already', lang, username=shown)) return event('addgamer_result', uid=user_id, username=typed_username, result='added', canonical=username) await self._reply(update, t('player_added', lang, username=shown)) def _ratings_keyboard(self, lang: str, waiting: bool = False) -> InlineKeyboardMarkup: """[📈 Рейтинги] under the /getgamers screen; ⏳ while the ratings are being fetched.""" if waiting: return InlineKeyboardMarkup([[InlineKeyboardButton(t('btn_wait', lang), callback_data="gm:wait")]]) return InlineKeyboardMarkup([[InlineKeyboardButton(t('btn_ratings', lang), callback_data="gm:ratings")]]) async def getgamers(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """ /getgamers — the state screen: one entry per player straight from the DB (bulk status + period), no request to Lichess, so it answers at once. Ratings are behind the 📈 button (handle_gamers_ratings). Several messages when the list is long; the button is on the last one. """ user_id = update.effective_user.id event('cmd', uid=user_id, name='getgamers') gamers = self.db.get_user_gamers(user_id) logger.info(f"getgamers: user_id={user_id}, found {len(gamers)} gamers") lang = self.get_user_language_from_update(update) self.counters.increment('getgamers') if not gamers: logger.info(f"getgamers: No gamers found for user {user_id}, sending no_players message") await self._reply(update, t('no_players', lang)) return messages = self._gamers_state_messages(gamers, lang) for i, text in enumerate(messages): markup = self._ratings_keyboard(lang) if i == len(messages) - 1 else None await self._reply(update, text, reply_markup=markup) logger.info(f"getgamers: sent {len(messages)} message(s) for user {user_id}, {len(gamers)} gamers") async def handle_gamers_ratings(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """ 📈 Рейтинги on the /getgamers screen (callback gm:ratings): the button turns into ⏳, the bullet/blitz/rapid ratings are fetched from Lichess (RATINGS_REQUEST_PAUSE apart, as before), and the message is redrawn with the
 table added and no button.
        """
        query = update.callback_query
        await query.answer()
        user_id = query.from_user.id
        event('cmd', uid=user_id, name='getgamers_ratings')
        lang = self._callback_lang(update)
        gamers = self.db.get_user_gamers(user_id)
        if not gamers:
            await query.edit_message_text(t('no_players', lang), parse_mode='HTML', disable_web_page_preview=True)
            return
        try:
            await query.edit_message_text(
                self._gamers_state_messages(gamers, lang)[-1], parse_mode='HTML',
                disable_web_page_preview=True, reply_markup=self._ratings_keyboard(lang, waiting=True)
            )
        except Exception as e:
            # e.g. "Message is not modified"; the fetch below still goes ahead
            logger.info(f"getgamers_ratings: could not show the ⏳ button for user {user_id}: {e}")
        table = StatsFormatter.format_gamers_table(await self._fetch_ratings(gamers))
        text = self._gamers_state_messages(gamers, lang, table=table)[-1]
        await query.edit_message_text(text, parse_mode='HTML', disable_web_page_preview=True)
        logger.info(f"getgamers_ratings: ratings of {len(gamers)} gamers shown to user {user_id}")

    async def handle_wait_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """The ⏳ placeholder button: just close the client's spinner."""
        await update.callback_query.answer()

    async def delgamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Show gamers list for deletion"""
        user_id = update.effective_user.id
        event('cmd', uid=user_id, name='delgamer')
        gamers = self.db.get_user_gamers(user_id)
        
        lang = self.get_user_language_from_update(update)
        if not gamers:
            await self._reply(update, t('no_players', lang))
            self.counters.increment('delgamer')
            return
        
        self.counters.increment('delgamer')
        
        # Show loading message
        loading_msg = await update.message.reply_text(t('loading_gamers', lang))
        
        # Create text message with stats (ratings from Lichess, "—" when missing)
        text_lines = []
        keyboard = []

        ratings_by_id = {r['id']: r for r in await self._fetch_ratings(gamers)}
        for gamer in gamers:
            username = gamer['username']
            ratings = ratings_by_id[gamer['id']]
            cell = lambda v: str(v) if v is not None else "—"
            mark = self._status_mark(gamer['id'])
            # The period is a property of the tracking, not of a closed / gone account
            period_text = "" if mark else f" · {format_period(gamer.get('period_minutes') or 0, lang)}"

            text_lines.append(
                f"{mark}{html.escape(username)}  "
                f"⚡ {cell(ratings['bullet'])}  🔥 {cell(ratings['blitz'])}  🐇 {cell(ratings['rapid'])}{period_text}"
            )

            # Add delete button
            keyboard.append([InlineKeyboardButton(
                text=f"🗑️ {username}",
                callback_data=f"delete_{gamer['id']}"
            )])
        
        gamers_text = t('select_gamer_to_delete', lang) + "\n".join(text_lines)
        
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        # Edit the loading message with the results
        try:
            await loading_msg.edit_text(
                gamers_text,
                parse_mode='HTML',
                reply_markup=reply_markup
            )
        except Exception as e:
            logger.error(f"Error editing message: {e}")
            try:
                await loading_msg.delete()
            except:
                pass
            await update.message.reply_text(
                gamers_text,
                parse_mode='HTML',
                reply_markup=reply_markup
            )
    
    async def handle_delete_gamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle gamer deletion"""
        query = update.callback_query
        await query.answer()
        
        user_id = query.from_user.id
        gamer_id = int(query.data.split('_')[1])
        
        # Get gamer info before deletion
        gamers = self.db.get_user_gamers(user_id)
        gamer_to_delete = next((g for g in gamers if g['id'] == gamer_id), None)
        
        # Для callback query получаем язык из БД
        if update.effective_user:
            self.db.add_or_get_telegram_user(
                user_id=update.effective_user.id,
                username=update.effective_user.username,
                first_name=update.effective_user.first_name,
                last_name=update.effective_user.last_name,
                language_code=update.effective_user.language_code
            )
        lang = self.db.get_user_language(user_id)
        if gamer_to_delete:
            username = gamer_to_delete['username']

            deleted = self.db.remove_user_gamer(user_id, gamer_id)

            if deleted:
                # Check how many gamers remain after deletion
                remaining_gamers = self.db.get_user_gamers(user_id)
                remaining_count = len(remaining_gamers)
                event('gamer_deleted', uid=user_id, gamer=username, remaining=remaining_count, via='delgamer')

                # Determine which message to show
                if remaining_count == 0:
                    # Last gamer deleted
                    message = t('last_gamer_deleted', lang, username=html.escape(username))
                else:
                    # Regular deletion
                    message = t('gamer_deleted', lang, username=html.escape(username))

                await query.edit_message_text(
                    message,
                    parse_mode='HTML'
                )
            else:
                await query.edit_message_text(t('delete_failed', lang))
        else:
            await query.edit_message_text(t('gamer_not_found', lang))

    @staticmethod
    def _stats_period_bounds(period: str, now_dt: datetime):
        """
        Local-time window of a /today, /yesterday or /week request as
        (since_dt, until_dt, want_rows), or None for an unknown period. The same
        boundaries are used for the bulk-status skip in get_stats and for the
        supplementary accuracy fetch (which also needs want_rows: a per-game
        breakdown only for today/yesterday). "week" is today-6 .. now, the
        window _is_date_in_range(days_back=7) uses.
        """
        today_midnight = now_dt.replace(hour=0, minute=0, second=0, microsecond=0)
        if period == "today":
            return today_midnight, now_dt, True
        if period == "yesterday":
            return today_midnight - timedelta(days=1), today_midnight, True
        if period == "week":
            return today_midnight - timedelta(days=6), now_dt, False
        return None

    @staticmethod
    def _stats_skip_reason(status, period_start_ts: float, now_ts: float):
        """
        Whether get_stats may skip a player without any Lichess request, from
        the player's bulk status (db.get_gamer_status, see player_status.py):
        'closed' for a disabled account, 'not_found' for one Lichess no longer
        knows (deleted or renamed), 'not_seen_since_period_start' when
        Lichess last saw the player online (seen_at, ms) before the period
        began — nobody plays or solves puzzles without being online, so such a
        player cannot have activity in the period. None means "process as
        before". A missing, stale (older than PeriodicMonitor.STATUS_MAX_AGE_SECONDS)
        or pre-window status (refreshed before period_start: it says nothing
        about the window) and a null seen_at never justify a skip.

        Why this matters: GET /api/user/{u}/activity is limited by Lichess to
        15 requests per 2 minutes per IP (lila Limiters.scala), independent of
        the games/user spacing, so a user tracking 16+ players always hit 429
        mid-command; on prod most of those players were not even online today.
        """
        if not status:
            return None
        checked_at = status.get('checked_at')
        if checked_at is None or now_ts - checked_at > PeriodicMonitor.STATUS_MAX_AGE_SECONDS:
            return None
        if checked_at < period_start_ts:
            return None
        if status.get('disabled'):
            return 'closed'
        if status.get('not_found'):
            return 'not_found'
        seen_at = status.get('seen_at')
        if seen_at is not None and seen_at / 1000 < period_start_ts:
            return 'not_seen_since_period_start'
        return None

    async def _collect_stats(self, user_id: int, gamers, period: str, bounds, lang: str):
        """
        The player blocks of /today, /yesterday, /week in the order of the
        list, as (blocks, skipped, with_activity). Per player, same requests
        and pauses as before: the bulk-status skip (_stats_skip_reason), the
        /stats/{u}/ request, for a player with activity the
        supplementary games/period fetch (accuracy, and the game rows for
        today/yesterday), 1 s before the next player. A player with no
        activity gets the "didn't play" line, a closed / gone one their status,
        a failed request the "could not get data" line.
        """
        since_dt, _, want_rows = bounds
        period_start_ts = since_dt.timestamp()
        blocks = []
        skipped = 0
        with_activity = 0
        for i, gamer in enumerate(gamers):
            username = gamer['username']
            shown = html.escape(username)

            # Bulk-status shortcut (see _stats_skip_reason): a player Lichess has not
            # seen online since the period started, or a closed account, gets no
            # activity request and no accuracy fetch.
            skip_reason = self._stats_skip_reason(self.db.get_gamer_status(gamer['id']), period_start_ts, time.time())
            if skip_reason:
                skipped += 1
                logger.info(f"⏭️ Skipping {username} for {period} (user {user_id}): {skip_reason}")
                event('stats_skip', uid=user_id, gamer=username, period=period, reason=skip_reason)
                if skip_reason == 'closed':
                    blocks.append(t('stats_status', lang, name=shown, status=t('status_closed', lang)))
                elif skip_reason == 'not_found':
                    blocks.append(t('stats_status', lang, name=shown, status=t('status_not_found', lang)))
                else:
                    blocks.append(t('stats_no_play', lang, name=shown))
                continue

            logger.info(f"🔍 Processing gamer {i+1}/{len(gamers)}: {username} for period {period}")

            # Get stats based on period
            try:
                logger.info(f"🔍 Making API request for {username}, period={period}")
                if period == "today":
                    data = await self.lichess_api.get_today_stats(username)
                elif period == "yesterday":
                    data = await self.lichess_api.get_yesterday_stats(username)
                else:  # week: the only remaining period (_stats_period_bounds validated it)
                    data = await self.lichess_api.get_week_stats(username)

                logger.info(f"🔍 API response for {username}: data={data is not None}, type={type(data)}")
                if isinstance(data, dict) and 'message' in data:
                    logger.info(f"🔍 API message: {data.get('message')}")
            except Exception as e:
                logger.error(f"❌ Error getting stats for {username}: {e}")
                import traceback
                logger.error(traceback.format_exc())
                data = None

            if data is None:
                logger.warning(f"⚠️ No response data for {username}: data is None")
                blocks.append(t('stats_error', lang, name=shown))
            else:
                # Check if there's activity (games in any mode or puzzles)
                api_data = data.get('data') or {}
                tasks = api_data.get('tasks') or {}
                games = api_data.get('games') or {}
                has_activity = (tasks.get('total', 0) or 0) > 0 or any(
                    g and (g.get('games_played', 0) or 0) > 0 for g in games.values()
                )
                logger.info(f"🔍 Activity check for {username}: has_activity={has_activity}")

                if has_activity:
                    # Дополнительный, параллельный запрос за реальными партиями периода —
                    # только чтобы добавить точность (accuracy) и, для today/yesterday,
                    # построчный разбор партий. Шапку (данные из /activity) не трогаем:
                    # при любой ошибке здесь просто не покажем строки партий.
                    accuracy_extra = None
                    try:
                        # Same window as the skip decision above (_stats_period_bounds),
                        # with "until" taken now, not when the command started.
                        _, until_dt, _ = self._stats_period_bounds(period, datetime.now())

                        accuracy_extra = await self.lichess_api.get_games_period(
                            username,
                            int(since_dt.timestamp() * 1000),
                            int(until_dt.timestamp() * 1000),
                            rated_only=True,
                            include_games=want_rows,
                            priority="interactive"
                        )
                    except Exception as e:
                        logger.warning(f"⚠️ Supplementary accuracy fetch failed for {username}/{period}: {e}")
                        accuracy_extra = None

                    block = StatsFormatter.format_player_stats(username, data, accuracy_extra, want_rows, lang)
                    if block is None:
                        block = t('stats_no_play', lang, name=shown)
                    else:
                        with_activity += 1
                    blocks.append(block)
                else:
                    logger.info(f"ℹ️ No activity found for {username}")
                    blocks.append(t('stats_no_play', lang, name=shown))

            # Add delay between requests to avoid rate limiting
            if i < len(gamers) - 1:
                await asyncio.sleep(1.0)
        return blocks, skipped, with_activity

    def _stats_keyboard(self, period: str, lang: str) -> InlineKeyboardMarkup:
        """The two other periods as buttons (st:): today -> [Вчера] [Неделя], etc."""
        buttons = [
            InlineKeyboardButton(t(f'btn_{p}', lang), callback_data=f"st:{p}")
            for p in ("today", "yesterday", "week") if p != period
        ]
        return InlineKeyboardMarkup([buttons])

    async def get_stats(self, update: Update, context: ContextTypes.DEFAULT_TYPE, period: str, query=None):
        """
        /today, /yesterday, /week (docs/design/product_concepts.md 2.8): ONE
        message "🔄 Собираю партии за сегодня…" that is edited into the result
        once all players are collected — a header with the date, a block per
        player (StatsFormatter.format_player_stats; "— не играл" for the
        rest), and the two other periods as buttons. If nobody played, just
        "📭 … никто не играл" with the buttons. A result longer than
        MAX_MESSAGE_CHARS is split at player boundaries; the buttons go on the
        last piece. With `query` (st: button) the same screen is
        redrawn in place of the pressed message.
        """
        user_id = update.effective_user.id
        started = time.monotonic()

        logger.info(f"🔍 get_stats called: user_id={user_id}, period={period}")

        # Get all gamers for this user
        gamers = self.db.get_user_gamers(user_id)
        logger.info(f"🔍 Found {len(gamers)} gamers for user {user_id}: {[g['username'] for g in gamers]}")

        if query is None:
            lang = self.get_user_language_from_update(update)
            send = lambda text, **kw: update.message.reply_text(text, parse_mode='HTML', disable_web_page_preview=True, **kw)
        else:
            lang = self._callback_lang(update)
            send = lambda text, **kw: query.message.reply_text(text, parse_mode='HTML', disable_web_page_preview=True, **kw)

        if not gamers:
            if query is None:
                await self._reply(update, t('no_players', lang))
            else:
                await query.edit_message_text(t('no_players', lang), parse_mode='HTML', disable_web_page_preview=True)
            event('stats', uid=user_id, period=period, players=0, skipped=0, with_activity=0,
                  took_s=time.monotonic() - started)
            return

        bounds = self._stats_period_bounds(period, datetime.now())
        if bounds is None:
            await send(t('unknown_period', lang))
            return

        # The one status message, edited into the result below
        loading = t(f'stats_collecting_{period}', lang)
        if query is None:
            status_msg = await send(loading)
            edit = status_msg.edit_text
        else:
            await query.edit_message_text(loading)
            edit = query.edit_message_text

        blocks, skipped, with_activity = await self._collect_stats(user_id, gamers, period, bounds, lang)

        if with_activity == 0:
            messages = [t(f'stats_nobody_{period}', lang)]
        else:
            messages = self._split_messages(StatsFormatter.format_stats_header(period, lang), blocks, sep="\n\n")
        keyboard = self._stats_keyboard(period, lang)
        for i, text in enumerate(messages):
            markup = keyboard if i == len(messages) - 1 else None
            if i > 0:
                await send(text, reply_markup=markup)
                continue
            try:
                await edit(text, parse_mode='HTML', disable_web_page_preview=True, reply_markup=markup)
            except Exception as e:
                # Status message gone (deleted by the user) or not editable: send anew
                logger.error(f"get_stats: could not edit the status message for user {user_id}: {e}")
                await send(text, reply_markup=markup)

        event('stats', uid=user_id, period=period, players=len(gamers), skipped=skipped,
              with_activity=with_activity, took_s=time.monotonic() - started)

        # Increment counter for the period command
        if period == "today":
            self.counters.increment('today')
        elif period == "yesterday":
            self.counters.increment('yesterday')
        elif period == "week":
            self.counters.increment('week')

    async def today(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Today command"""
        event('cmd', uid=update.effective_user.id, name='today')
        await self.get_stats(update, context, "today")

    async def yesterday(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Yesterday command"""
        event('cmd', uid=update.effective_user.id, name='yesterday')
        await self.get_stats(update, context, "yesterday")

    async def week(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Week command"""
        event('cmd', uid=update.effective_user.id, name='week')
        await self.get_stats(update, context, "week")

    async def handle_stats_nav(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """[📅 Вчера] / [📅 Неделя] / [📅 Сегодня] under a stats screen (st:): redraw it for that period."""
        query = update.callback_query
        await query.answer()
        period = query.data.split(':', 1)[1]
        event('cmd', uid=query.from_user.id, name=period, via='button')
        await self.get_stats(update, context, period, query=query)

    async def support(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Support command - show contact information"""
        event('cmd', uid=update.effective_user.id, name='support')
        lang = self.get_user_language_from_update(update)
        support_msg = t('support_message', lang, version=BOT_VERSION)
        await update.message.reply_text(support_msg, parse_mode='HTML')
        self.counters.increment('support')
    
    async def last_year_or_1000games(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Get last year stats or last 1000 rated games for all players with activity"""
        user_id = update.effective_user.id
        event('cmd', uid=user_id, name='lastyear')

        # Get all gamers for this user
        gamers = self.db.get_user_gamers(user_id)
        
        lang = self.get_user_language_from_update(update)
        if not gamers:
            await self._reply(update, t('no_players', lang))
            return
        
        now_ms = int(time.time() * 1000)
        year_ms = 365 * 24 * 3600 * 1000
        since_ms = now_ms - year_ms
        
        has_any_activity = False
        
        # Process each gamer sequentially
        for i, gamer in enumerate(gamers):
            username = gamer['username']
            
            try:
                # Send message about processing this player
                processing_msg = None
                try:
                    processing_msg = await update.message.reply_text(t('last_year_1000_player_processing', lang, username=username), parse_mode='HTML')
                except Exception:
                    pass
                
                # Get data for this player
                # User-initiated command: jump ahead of the periodic backlog in the
                # shared-token queue instead of waiting it out as "background".
                data = await self.lichess_api.get_games_period(username, since_ms, now_ms, rated_only=True, priority="interactive")
                
                # Delete processing message
                if processing_msg:
                    try:
                        await processing_msg.delete()
                    except Exception:
                        pass
                
                if data:
                    # Check if there's activity (games_count > 0)
                    games_count = data.get('games_count', 0)
                    if games_count > 0:
                        # Format and send immediately
                        text = StatsFormatter.format_last_year_or_1000(data, username, lang)
                        await update.message.reply_text(text, parse_mode='HTML')
                        has_any_activity = True

                # Wait 3 seconds before next request (except after the last one)
                if i < len(gamers) - 1:
                    await asyncio.sleep(3.0)

            except Exception as e:
                logger.error(f"/lastYear_or_1000games error for {username}: {e}")
                await update.message.reply_text(t('stats_error', lang, name=html.escape(username)), parse_mode='HTML')
        
        # If no activity for any player
        if not has_any_activity:
            await update.message.reply_text(t('no_activity', lang))
        
        self.counters.increment('last_year_1000')
    
    async def setperiod(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Set period command - first select gamer, then select period"""
        user_id = update.effective_user.id
        event('cmd', uid=user_id, name='setperiod')

        # Get all gamers for this user
        gamers = self.db.get_user_gamers(user_id)
        
        lang = self.get_user_language_from_update(update)
        if not gamers:
            await self._reply(update, t('no_players', lang))
            self.counters.increment('setperiod')
            return
        
        # Create keyboard with gamers and their periods
        keyboard = []
        
        for gamer in gamers:
            username = gamer['username']
            # The one spelling of a period (format_period), as on the /getgamers screen
            period_text = format_period(gamer.get('period_minutes') or 0, lang)

            keyboard.append([InlineKeyboardButton(
                text=f"{username} · {period_text}",
                callback_data=f"select_gamer_period_{gamer['id']}"
            )])
        
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        await update.message.reply_text(
            t('select_player_period', lang),
            reply_markup=reply_markup
        )
        self.counters.increment('setperiod')
    
    async def select_gamer_for_period(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle gamer selection for period setting"""
        query = update.callback_query
        await query.answer()
        
        logger.info(f"select_gamer_for_period called with callback_data: {query.data}")
        
        user_id = query.from_user.id
        # Parse callback_data: select_gamer_period_{gamer_id}
        try:
            gamer_id = int(query.data.split('_')[-1])
            logger.info(f"Parsed gamer_id: {gamer_id}")
        except (ValueError, IndexError) as e:
            logger.error(f"Error parsing gamer_id from callback_data '{query.data}': {e}")
            await query.edit_message_text("❌ Error: Invalid player selection")
            return
        
        # Get gamer info
        gamers = self.db.get_user_gamers(user_id)
        selected_gamer = None
        for gamer in gamers:
            if gamer['id'] == gamer_id:
                selected_gamer = gamer
                break
        
        if not selected_gamer:
            await query.edit_message_text("❌ Player not found")
            return
        
        # Для callback query получаем язык из БД
        if update.effective_user:
            self.db.add_or_get_telegram_user(
                user_id=update.effective_user.id,
                username=update.effective_user.username,
                first_name=update.effective_user.first_name,
                last_name=update.effective_user.last_name,
                language_code=update.effective_user.language_code
            )
        lang = self.db.get_user_language(user_id)
        
        # Show period options for selected gamer
        keyboard = []
        for period in PERIOD_OPTIONS:
            if period == 0:
                button_text = t('disable_notifications', lang)
            else:
                button_text = f"⏰ {format_period(period, lang)}"
            keyboard.append([InlineKeyboardButton(
                button_text, 
                callback_data=f"period_{gamer_id}_{period}"
            )])
        
        reply_markup = InlineKeyboardMarkup(keyboard)
        await query.edit_message_text(
            t('select_period', lang, username=selected_gamer['username']),
            reply_markup=reply_markup,
            parse_mode='HTML'
        )
    
    async def select_period(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle period selection"""
        query = update.callback_query
        await query.answer()
        
        user_id = query.from_user.id
        # Parse callback data: period_{gamer_id}_{period}
        parts = query.data.split('_')
        gamer_id = int(parts[1])
        period = int(parts[2])
        
        # Get gamer info
        gamers = self.db.get_user_gamers(user_id)
        selected_gamer = None
        for gamer in gamers:
            if gamer['id'] == gamer_id:
                selected_gamer = gamer
                break
        
        if not selected_gamer:
            await query.edit_message_text("❌ Player not found")
            return
        
        # Для callback query получаем язык из БД
        if update.effective_user:
            self.db.add_or_get_telegram_user(
                user_id=update.effective_user.id,
                username=update.effective_user.username,
                first_name=update.effective_user.first_name,
                last_name=update.effective_user.last_name,
                language_code=update.effective_user.language_code
            )
        lang = self.db.get_user_language(user_id)
        
        # Set period for this user-gamer pair
        self.db.set_user_gamer_period(user_id, gamer_id, period)
        event('period_set', uid=user_id, gamer=selected_gamer['username'], minutes=period)

        if period == 0:
            # Отключаем мониторинг: чистим чекпоинт, чтобы при повторном включении
            # не было catch-up на потенциально очень старое (устаревшее) окно.
            self.db.clear_period_checkpoint(user_id, gamer_id)
            await self.monitor.stop_periodic_task(gamer_id, user_id)
            await query.edit_message_text(
                t('notifications_disabled', lang, username=selected_gamer['username'])
            )
        else:
            await query.edit_message_text(
                t('period_set_confirm', lang, period=format_period(period, lang), username=selected_gamer['username'])
            )
            
            # Start periodic task for this gamer (send to user's personal messages)
            await self.monitor.start_periodic_task(selected_gamer, user_id, period)
    
    async def set_lang(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Show language selection menu"""
        user = update.effective_user
        if not user:
            await update.message.reply_text("❌ Failed to get user information")
            return
        # /lang is the short alias of /set_lang (both registered on this handler)
        text = update.message.text or ''
        event('cmd', uid=user.id, name='lang' if text.lower().startswith('/lang') else 'set_lang')

        # Get current language to show menu in user's language
        lang = self.get_user_language_from_update(update)
        
        # Short buttons, two per row, in LANGUAGES order
        buttons = [InlineKeyboardButton(t(f'btn_lang_{code}', lang), callback_data=f"lang_{code}")
                   for code in LANGUAGES]
        keyboard = [buttons[i:i + 2] for i in range(0, len(buttons), 2)]
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        await update.message.reply_text(
            t('lang_prompt', lang),
            reply_markup=reply_markup,
            parse_mode='HTML'
        )
    
    async def handle_language_selection(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle language selection callback"""
        query = update.callback_query
        await query.answer()
        
        user = query.from_user
        user_id = user.id
        selected_lang = query.data.split('_', 1)[1]  # one of LANGUAGES
        
        # Update user info in database
        self.db.add_or_get_telegram_user(
            user_id=user_id,
            username=user.username,
            first_name=user.first_name,
            last_name=user.last_name,
            language_code=user.language_code
        )
        
        # Save selected language to database
        success = self.db.set_user_language(user_id, selected_lang)

        if success:
            event('lang_set', uid=user_id, lang=selected_lang, via='lang')
            # Confirmation in the selected language
            await query.edit_message_text(t(f'language_set_{selected_lang}', selected_lang))
        else:
            # Use current language for error message
            lang = self.db.get_user_language(user_id)
            await query.edit_message_text(t('language_set_failed', lang))
    
    async def profile(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Show list of players to view their profiles"""
        user_id = update.effective_user.id
        event('cmd', uid=user_id, name='profile')
        gamers = self.db.get_user_gamers(user_id)
        
        lang = self.get_user_language_from_update(update)
        
        if not gamers:
            await self._reply(update, t('no_players', lang))
            return
        
        # Create keyboard with player buttons
        keyboard = []
        for gamer in gamers:
            username = gamer['username']
            keyboard.append([
                InlineKeyboardButton(
                    username,
                    callback_data=f"profile_{gamer['id']}"
                )
            ])
        
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        await update.message.reply_text(
            t('select_player_profile', lang),
            reply_markup=reply_markup,
            parse_mode='HTML'
        )
    
    async def handle_profile_selection(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Handle profile selection callback - send profile link"""
        query = update.callback_query
        await query.answer()
        
        user_id = query.from_user.id
        gamer_id = int(query.data.split('_')[1])
        
        # Get gamer info
        gamers = self.db.get_user_gamers(user_id)
        selected_gamer = next((g for g in gamers if g['id'] == gamer_id), None)
        
        if not selected_gamer:
            lang = self.db.get_user_language(user_id)
            await query.edit_message_text(t('gamer_not_found', lang))
            return
        
        username = selected_gamer['username']
        profile_url = f"https://lichess.org/@/{username}"
        
        lang = self.db.get_user_language(user_id)
        
        # Send profile link
        await query.message.reply_text(
            f"🔗 {profile_url}",
            parse_mode='HTML'
        )
        
        # Edit original message to show confirmation
        await query.edit_message_text(
            t('profile_link_sent', lang),
            parse_mode='HTML'
        )
    
    async def log_incoming_update(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """One INFO line per incoming update (runs before all other handlers, never blocks them)."""
        user = update.effective_user
        uid = user.id if user else None
        if update.callback_query:
            logger.info(f"⬅️ callback from user {uid}: {update.callback_query.data!r}")
            event('callback', uid=uid, data=update.callback_query.data)
        elif update.message:
            msg = update.message
            if msg.text is not None:
                logger.info(f"⬅️ text from user {uid}: {msg.text[:80]!r}")
                # Commands are recorded by their handlers ("cmd" lines); here only plain
                # text. What was made of it is the addgamer_input line (handle_username),
                # unless the /addtoken conversation consumed it as a token.
                if not msg.text.startswith('/'):
                    event('text', uid=uid, len=len(msg.text))
            else:
                kind = next((k for k in ('photo', 'sticker', 'document', 'contact', 'voice', 'video', 'location')
                             if getattr(msg, k, None)), 'other')
                logger.info(f"⬅️ non-text message ({kind}) from user {uid}")
                event('non_text', uid=uid, kind=kind)
        else:
            logger.info(f"⬅️ update of another type from user {uid}")

    async def handle_non_text(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """Photos, stickers, contacts etc. used to be ignored silently; tell the user what we accept."""
        lang = self.get_user_language_from_update(update)
        await self._reply(update, t('non_text_hint', lang))

    async def handle_unknown_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        """A command no handler matched (/foo, a typo) used to leave no trace at all; point to /help."""
        text = update.message.text or ''
        event('cmd', uid=update.effective_user.id, name='unknown', text=text[:40])
        lang = self.get_user_language_from_update(update)
        await self._reply(update, t('unknown_command', lang))

    async def set_bot_commands(self, application: Application):
        """
        Command menu (the BotFather /setcommands list) from onboarding.BOT_COMMANDS:
        the default (en) list, then one list per other language of LANGUAGES for
        clients whose Telegram language is that one (ru, uz, tr, fa, ar), so they
        see it in their language without a manual BotFather step.
        Called from post_init; a Telegram failure must never stop the bot.
        """
        try:
            menus = [('en', None)] + [(lang, lang) for lang in LANGUAGES if lang != 'en']
            for lang, code in menus:
                await application.bot.set_my_commands(
                    [BotCommand(cmd, desc) for cmd, desc in BOT_COMMANDS[lang]], language_code=code
                )
            logger.info("Bot command menu set (en default, " + ", ".join(c for _, c in menus if c) + ")")
        except Exception as e:
            logger.warning(f"set_my_commands failed, the command menu stays as it was: {e}")

    def setup_handlers(self, application: Application):
        """Setup all handlers"""
        self.application = application  # Store application reference
        self.monitor.application = application  # periodic notifications go out via application.bot

        # Group -1 runs before group 0 and does not stop it: a single log line per update
        application.add_handler(TypeHandler(Update, self.log_incoming_update), group=-1)
        
        # Conversation handler for addtoken (token required)
        # Must be added BEFORE general MessageHandler to avoid conflicts
        addtoken_conv = ConversationHandler(
            entry_points=[CommandHandler("addtoken", self.addtoken_start)],
            states={
                WAITING_FOR_TOKEN: [
                    MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_token),
                    # every command except the fallbacks below leaves the conversation
                    # and is dispatched through self._command_callbacks
                    MessageHandler(filters.COMMAND & ~filters.Regex(r'^/(cancel|addtoken)(@\w+)?(\s|$)'),
                                   self.addtoken_leave),
                ],
            },
            fallbacks=[
                # Must be a coroutine: PTB 20 awaits the callback, and the earlier
                # sync lambda raised "object int can't be used in 'await'" on every
                # /cancel, leaving the conversation open.
                CommandHandler("cancel", self.addtoken_cancel),
                CommandHandler("addtoken", self.addtoken_start)  # Allow restarting conversation
            ],
            per_chat=True,
            per_user=True
        )
        
        # The conversation goes first so that, while a user is inside /addtoken, the
        # WAITING_FOR_TOKEN handlers above see every command before the plain
        # CommandHandlers below do (otherwise /start would run but leave the
        # conversation open, and the next name would again be "not a token").
        application.add_handler(addtoken_conv)

        # Command → callback map: registered as CommandHandlers below and used by
        # addtoken_leave to run the command that ended the conversation.
        self._command_callbacks = {
            'start': self.start,
            'help': self.help_command,
            'addgamer': self.addgamer_command,
            'getgamers': self.getgamers,
            'delgamer': self.delgamer,
            'today': self.today,
            'yesterday': self.yesterday,
            'week': self.week,
            # /year is the short alias; the long name keeps working for old users
            'year': self.last_year_or_1000games,
            'lastyear_or_1000games': self.last_year_or_1000games,
            'support': self.support,
            'setperiod': self.setperiod,
            'lang': self.set_lang,
            'set_lang': self.set_lang,
            'profile': self.profile,
            'test_admin_notify': self.test_admin_notify,
            'cancel': self.cancel_nothing,
        }
        application.add_handler(CommandHandler("start", self.start))
        application.add_handler(CommandHandler("help", self.help_command))
        application.add_handler(CommandHandler("addgamer", self.addgamer_command))
        # Any other text in a private chat is a player name (no /addgamer needed first)
        application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_username))
        application.add_handler(CommandHandler("getgamers", self.getgamers))
        application.add_handler(CommandHandler("delgamer", self.delgamer))
        application.add_handler(CommandHandler("today", self.today))
        application.add_handler(CommandHandler("yesterday", self.yesterday))
        application.add_handler(CommandHandler("week", self.week))
        application.add_handler(CommandHandler(["year", "lastYear_or_1000games"], self.last_year_or_1000games))
        application.add_handler(CommandHandler("support", self.support))
        application.add_handler(CommandHandler("setperiod", self.setperiod))
        application.add_handler(CommandHandler(["lang", "set_lang"], self.set_lang))
        application.add_handler(CommandHandler("profile", self.profile))
        application.add_handler(CommandHandler("test_admin_notify", self.test_admin_notify))
        # /cancel with no conversation open (the addtoken texts advertise it)
        application.add_handler(CommandHandler("cancel", self.cancel_nothing))
        
        # Callback handlers (order matters - more specific patterns first).
        # addgamer_how / start_lang_* / lang_* carry no state in user_data, so the
        # buttons keep working after a bot restart.
        application.add_handler(CallbackQueryHandler(self.addgamer_show_help, pattern="^addgamer_how$"))
        lang_codes = "|".join(LANGUAGES)
        application.add_handler(CallbackQueryHandler(self.handle_start_lang, pattern=f"^start_lang_({lang_codes})$"))
        application.add_handler(CallbackQueryHandler(self.handle_language_selection, pattern=f"^lang_({lang_codes})$"))
        application.add_handler(CallbackQueryHandler(self.handle_profile_selection, pattern="^profile_"))
        application.add_handler(CallbackQueryHandler(self.select_gamer_for_period, pattern="^select_gamer_period_"))
        application.add_handler(CallbackQueryHandler(self.handle_delete_gamer, pattern="^delete_"))
        application.add_handler(CallbackQueryHandler(self.select_period, pattern="^period_"))
        # Iteration 1 screens (docs/design/product_concepts.md): the ratings
        # button of /getgamers, the "quiet player" question, the period
        # buttons under /today. All stateless: they keep working after a restart.
        application.add_handler(CallbackQueryHandler(self.handle_gamers_ratings, pattern="^gm:ratings$"))
        application.add_handler(CallbackQueryHandler(self.handle_wait_button, pattern="^gm:wait$"))
        application.add_handler(CallbackQueryHandler(self.handle_stats_nav, pattern="^st:(today|yesterday|week)$"))

        # Anything that is a private message but not text/command (photo of a profile,
        # sticker, contact...) — last in group 0, so it only fires when nothing else matched
        application.add_handler(MessageHandler(
            filters.ChatType.PRIVATE & ~filters.TEXT & ~filters.COMMAND & ~filters.StatusUpdate.ALL,
            self.handle_non_text
        ))

        # Unknown command (/foo): also last in group 0, after every CommandHandler
        # and the addtoken ConversationHandler (whose /cancel and /addtoken
        # fallbacks are matched there first), so a registered command never
        # reaches it. Private chats only, like the non-text hint.
        application.add_handler(MessageHandler(
            filters.COMMAND & filters.ChatType.PRIVATE,
            self.handle_unknown_command
        ))

def main():
    """Main function"""
    bot = LichessBot()

    # No persistence any more: the add-player flow has no state (any text is a
    # name), and the /addtoken conversation never had it. An old
    # bot_persistence.pickle next to the DB is simply ignored.
    # Create application with Long Polling configuration
    application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
    
    # Setup handlers
    bot.setup_handlers(application)
    
    # Set application reference for periodic tasks
    bot.application = application
    bot.monitor.application = application
    
    # After the application starts: the command menu (never fatal, see
    # set_bot_commands), then the periodic tasks for existing gamers
    async def post_init(app):
        await bot.set_bot_commands(app)
        await bot.monitor.start_existing_periodic_tasks()
    
    application.post_init = post_init
    
    # Add error handler
    async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
        """Log the error with its real traceback and which update triggered it."""
        # traceback.format_exc() here printed "NoneType: None": the error handler runs
        # outside the except block, so the traceback has to come from context.error itself.
        who = ""
        uid = None
        what = type(update).__name__
        if isinstance(update, Update):
            user = update.effective_user
            uid = user.id if user else None
            what = (update.message.text[:60] if update.message and update.message.text
                    else (update.callback_query.data if update.callback_query else type(update).__name__))
            who = f" (user {uid}, update: {what!r})"
        logger.error(f"Exception while handling an update{who}: {context.error!r}", exc_info=context.error)
        event('tg_error', uid=uid, handler=what, error=repr(context.error)[:80])
    
    application.add_error_handler(error_handler)
    
    # Start the bot with Long Polling
    logger.info("Starting Lichess Statistics Bot with Long Polling...")
    try:
        application.run_polling(
            poll_interval=POLL_INTERVAL,
            timeout=POLL_TIMEOUT,
            drop_pending_updates=DROP_PENDING_UPDATES,
            allowed_updates=ALLOWED_UPDATES
        )
    except Exception as e:
        logger.error(f"Fatal error in run_polling: {e}")
        import traceback
        logger.error(traceback.format_exc())
        raise

if __name__ == '__main__':
    main()