""" Text of the report (periodic notification), of /today, /yesterday, /week and of /year, and the ratings table of /getgamers. Layouts and rules: docs/design/product_concepts.md 2.5 (report), 2.8 (/today). Everything here is HTML (parse_mode='HTML' in the callers): the player's name goes through html.escape and into , the game rows into one
 block so
the columns line up; titles and mode lines are plain text. No line except the
one with the name is longer than 34 characters (an emoji counts as 2), see
tests/bot/test_report.py.
"""
from typing import Dict, Any, Optional, List, Tuple
from datetime import datetime, timedelta
import html
from i18n import t, format_count, format_day, format_day_range

# Modes in the order their lines appear; game rows exist for ROW_MODES only
# (bullet gets the mode line only — the rows would be noise).
MODE_ORDER = ('bullet', 'blitz', 'rapid', 'classical')
ROW_MODES = ('blitz', 'rapid', 'classical')
# Game rows per report; the rest is "…и ещё N партий — /today"
MAX_REPORT_ROWS = 10
# Only a window this long (after downtime) gets the "over the last N hours" line
SPAN_NOTE_MINUTES = 6 * 60
SPAN_DAYS_MINUTES = 48 * 60

MODE_EMOJI = {
    'bullet': '⚡',
    'blitz': '🔥',
    'rapid': '🐇',
    'classical': '♟️',
    'correspondence': '📮',
}


class StatsFormatter:
    @staticmethod
    def _get_game_type_emoji(game_type: str) -> str:
        """Emoji of a game mode (⚡ Bullet, 🔥 Blitz, 🐇 Rapid, ♟️ Classical)."""
        return MODE_EMOJI.get(game_type.lower(), '🎯')

    @staticmethod
    def _format_accuracy(accuracy: Optional[float]) -> str:
        """"91 %", or "—" when the game was not analysed."""
        if accuracy is None:
            return "—"
        return f"{accuracy:.0f} %"

    @staticmethod
    def _format_signed(change: Optional[int]) -> str:
        """Rating change of a mode line: "+12", "−4" (U+2212), "0"; "—" if unknown."""
        if change is None:
            return "—"
        if change > 0:
            return f"+{change}"
        if change < 0:
            return f"−{-change}"
        return "0"

    @staticmethod
    def _format_row_diff(diff: Optional[int]) -> str:
        """± column of a game row: "+8", "-9", "0"; "?" when the service had no ratingDiff."""
        if diff is None:
            return "?"
        if diff > 0:
            return f"+{diff}"
        return str(diff)

    @staticmethod
    def _format_row_outcome_circle(row: dict) -> str:
        """
        Colored circle for the tracked user's outcome in this row:
        🟢 win, 🔴 loss, ⚪ draw (or unknown side).
        """
        tracked_is_white = row.get('tracked_is_white')
        result = row.get('result', '')
        if tracked_is_white is None or result == "1/2-1/2":
            return "⚪"
        tracked_won = (result == "1-0" and tracked_is_white) or (result == "0-1" and not tracked_is_white)
        return "🟢" if tracked_won else "🔴"

    @staticmethod
    def format_game_rows(rows: List[dict], lang: str = 'en') -> str:
        """
        The game rows of a report with their column header, one line per game:

               ±   цвет   точн.  соперник
            🟢 +8  белые  91 %   2990 · 79 %
            ⚪  0  чёрные    —   3102 · —

        Columns: outcome (🟢/🔴/⚪), the tracked player's ratingDiff in the game
        (right-aligned, 2 wide; "?" if unknown), the colour they played as a
        word (6 wide; "?" if the side is unknown), their accuracy (right-aligned,
        4 wide; "—" if not analysed), then " · ". The widths grow only when a value does not fit (a 3-digit
        diff, "100 %"), and the header follows. The caller wraps the result in
        
; the longest line of the layout above is 32 characters with the
        emoji counted as 2.
        """
        if not rows:
            return ""

        white_word = t('colour_white', lang)
        black_word = t('colour_black', lang)
        prepared = []
        for row in rows:
            circle = StatsFormatter._format_row_outcome_circle(row)
            tracked_is_white = row.get('tracked_is_white')
            if tracked_is_white is None:
                colour = "?"
            else:
                colour = white_word if tracked_is_white else black_word
            # Unknown side: read the row from White's point of view, as before
            if tracked_is_white is not False:
                my_acc = row.get('white_accuracy')
                opp_rating = row.get('black_rating')
                opp_acc = row.get('black_accuracy')
            else:
                my_acc = row.get('black_accuracy')
                opp_rating = row.get('white_rating')
                opp_acc = row.get('white_accuracy')
            opp_rating_s = str(opp_rating) if opp_rating is not None else "—"
            prepared.append((
                circle,
                StatsFormatter._format_row_diff(row.get('tracked_rating_diff')),
                colour,
                StatsFormatter._format_accuracy(my_acc),
                opp_rating_s,
                StatsFormatter._format_accuracy(opp_acc),
            ))

        diff_w = max(2, max(len(p[1]) for p in prepared))
        acc_w = max(4, max(len(p[3]) for p in prepared))
        colour_w = max(6, max(len(p[2]) for p in prepared))

        # Header: "±" over the diff column, the words over their columns. The
        # accuracy header is left-aligned over a right-aligned column and is
        # followed by 2 spaces, so "acc." / "точн." both end where the rows'
        # 3-space gap before the opponent does.
        header = (
            f"   ±{' ' * (diff_w - 2)}   {t('hdr_colour', lang):<{colour_w}} "
            f"{t('hdr_accuracy', lang):<{max(acc_w + 1, 5)}}  {t('hdr_opponent', lang)}"
        )
        lines = [header]
        for circle, diff, colour, acc, opp_rating, opp_acc in prepared:
            lines.append(f"{circle} {diff:>{diff_w}}  {colour:<{colour_w}} {acc:>{acc_w}}   {opp_rating} · {opp_acc}")
        return "\n".join(lines)

    @staticmethod
    def format_mode_line(mode: str, stats: Dict[str, Any], lang: str = 'en', with_wins: bool = True) -> str:
        """
        "🔥 Blitz 3105 (+12) · 3 из 5 побед": emoji, mode, rating after the
        window (final_rating, or rating from games/period; "—" if unknown),
        the change in brackets and, for 2+ games, the wins. The games count of
        the mode is implied by the rows / the title, so it is not repeated.
        """
        rating = stats.get('final_rating', stats.get('rating'))
        line = t('mode_line', lang,
                 emoji=StatsFormatter._get_game_type_emoji(mode),
                 mode=mode.title(),
                 rating=rating if rating is not None else "—",
                 change=StatsFormatter._format_signed(stats.get('rating_change')))
        games = stats.get('games_played', 0) or 0
        if with_wins and games >= 2:
            line += t('mode_wins', lang, wins=stats.get('wins', 0), n=games)
        return line

    @staticmethod
    def _modes_and_rows(stats_by_mode: Optional[Dict[str, Any]], want_rows: bool):
        """
        (modes, rows) from a games-by-mode dict ({'blitz': {...}, ...}, the
        'data' of games/period or the 'games' of /activity): modes = [(mode,
        stats)] with games in MODE_ORDER; rows = the game rows of ROW_MODES,
        chronological within a mode, modes in the same order as the mode lines.
        """
        modes = []
        rows = []
        if not stats_by_mode:
            return modes, rows
        for mode in MODE_ORDER:
            stats = stats_by_mode.get(mode)
            if not stats or (stats.get('games_played', 0) or 0) <= 0:
                continue
            modes.append((mode, stats))
            if want_rows and mode in ROW_MODES:
                mode_rows = stats.get('games') or []
                rows.extend(sorted(mode_rows, key=lambda r: r.get('created_at') or 0))
        return modes, rows

    @staticmethod
    def _player_block(name: str, modes: List[Tuple[str, Dict[str, Any]]], rows: List[dict],
                      puzzles: Optional[Tuple[int, int]], lang: str, report: bool,
                      max_rows: Optional[int] = None, note: Optional[str] = None) -> Optional[str]:
        """
        One player's block, shared by the report (report=True: ♟️ in the title,
        blank lines around the rows and the puzzles) and /today (compact, no
        emoji in the title). `puzzles` is (solved, total) or None. None when
        there is nothing to show (no games, no puzzles).
        """
        shown = html.escape(name)
        total_games = sum((s.get('games_played', 0) or 0) for _, s in modes)
        has_puzzles = bool(puzzles) and puzzles[1] > 0
        if total_games == 0 and not has_puzzles:
            return None

        lines = []
        if total_games == 0:
            # Puzzles only: the numbers go into the title, no puzzles line below
            key = 'report_title_puzzles' if report else 'stats_title_puzzles'
            lines.append(t(key, lang, name=shown, solved=puzzles[0], total=puzzles[1]))
            if note:
                lines.append(note)
            return "\n".join(lines)

        key = 'report_title' if report else 'stats_title'
        lines.append(t(key, lang, name=shown, games=format_count(total_games, 'games', lang)))
        if note:
            lines.append(note)
        for mode, stats in modes:
            lines.append(StatsFormatter.format_mode_line(mode, stats, lang))

        if rows:
            shown_rows = rows[:max_rows] if max_rows else rows
            if report:
                lines.append("")
            lines.append("
" + StatsFormatter.format_game_rows(shown_rows, lang) + "
") rest = len(rows) - len(shown_rows) if rest > 0: lines.append(t('report_more_games', lang, games=format_count(rest, 'games', lang))) if has_puzzles: if report: lines.append("") lines.append(t('puzzles_line', lang, solved=puzzles[0], total=puzzles[1])) return "\n".join(lines) @staticmethod def _puzzles_of_period(puzzles_data: Optional[Dict[str, Any]]) -> Optional[Tuple[int, int]]: """(solved, total) from a /puzzle/period answer, or None without attempts.""" if not puzzles_data: return None info = puzzles_data.get('data') or {} total = puzzles_data.get('puzzles_in_period') or 0 if total <= 0: total = info.get('total_attempts') or 0 if total <= 0: return None return (info.get('solved') or 0, total) @staticmethod def _span_note(span_minutes: Optional[int], lang: str) -> Optional[str]: """"за последние 6 часов" for a window of 6+ hours (days from 48 h), else None.""" if not span_minutes or span_minutes < SPAN_NOTE_MINUTES: return None if span_minutes >= SPAN_DAYS_MINUTES: span = format_count(max(2, round(span_minutes / 1440)), 'days', lang) else: span = format_count(round(span_minutes / 60), 'hours', lang) return t('report_span', lang, span=span) @staticmethod def format_report(username: str, games_data: Optional[Dict[str, Any]], puzzles_data: Optional[Dict[str, Any]], span_minutes: int, lang: str = 'en') -> str: """ The periodic report (product_concepts.md 2.5), HTML: ♟️ DrNykterstein — 5 партий 🔥 Blitz 3105 (+12) · 3 из 5 побед
   ±   цвет   точн.  соперник
            🟢 +8  белые  91 %   2990 · 79 %
🧩 Пазлы: 14 из 17 решены /today — весь день games_data is the games/period answer (include_games=True), puzzles_data the puzzle/period answer or None, span_minutes the real length of the queried window: from 6 hours (a catch-up after downtime) a second line "за последние N часов" is added, days from 48 hours. At most MAX_REPORT_ROWS game rows, then "…и ещё N партий — /today". Without games and puzzles the no_activity text is returned (the caller does not send in that case). """ stats_by_mode = (games_data or {}).get('data') or {} modes, rows = StatsFormatter._modes_and_rows(stats_by_mode, want_rows=True) block = StatsFormatter._player_block( username, modes, rows, StatsFormatter._puzzles_of_period(puzzles_data), lang, report=True, max_rows=MAX_REPORT_ROWS, note=StatsFormatter._span_note(span_minutes, lang) ) if block is None: return t('no_activity', lang) return block + "\n\n" + t('report_footer', lang) @staticmethod def format_player_stats(username: str, activity_data: Optional[Dict[str, Any]], games_extra: Optional[Dict[str, Any]], want_rows: bool, lang: str = 'en') -> Optional[str]: """ One player's block of /today, /yesterday, /week (product_concepts.md 2.8), built like the report but without ♟️ and compact. activity_data is the /stats/{u}/ answer (mode lines and puzzles come from it), games_extra the games/period answer that supplies the game rows (today/yesterday only, want_rows) — None just means no rows. None when the player had no games and no puzzles. """ api_data = (activity_data or {}).get('data') or {} modes, _ = StatsFormatter._modes_and_rows(api_data.get('games') or {}, want_rows=False) rows = [] if want_rows and games_extra: _, rows = StatsFormatter._modes_and_rows(games_extra.get('data') or {}, want_rows=True) tasks = api_data.get('tasks') or {} puzzles = None if (tasks.get('total') or 0) > 0: puzzles = (tasks.get('solved') or 0, tasks['total']) return StatsFormatter._player_block(username, modes, rows, puzzles, lang, report=False) @staticmethod def format_stats_header(period: str, lang: str = 'en', now: Optional[datetime] = None) -> str: """"📊 Сегодня, 21 октября" / "📊 Вчера, 20 октября" / "📊 Неделя, 15–21 октября".""" now = now or datetime.now() today = now.date() if period == "yesterday": return t('stats_head_yesterday', lang, date=format_day(today - timedelta(days=1), lang, today)) if period == "week": return t('stats_head_week', lang, range=format_day_range(today - timedelta(days=6), today, lang, today)) return t('stats_head_today', lang, date=format_day(today, lang, today)) @staticmethod def format_gamers_table(gamers_data: list) -> str: """ Column-aligned monospace table behind the 📈 Ratings button of /getgamers: username, then bullet/blitz/rapid ratings ("—" when the player has no rating in a mode or Lichess did not answer). Column widths are computed from the actual data so every column lines up character-for-character. Caller is expected to wrap the result in an HTML
 block so Telegram renders it with a monospace font (username can't be
        bolded there — pre/code entities can't contain other entities).
        """
        if not gamers_data:
            return ""

        def cell(value) -> str:
            return str(value) if value is not None else "—"

        rows = [(html.escape(str(g['username'])), cell(g.get('bullet')), cell(g.get('blitz')), cell(g.get('rapid')))
                for g in gamers_data]

        name_width = max(len(r[0]) for r in rows)
        bullet_width = max(len(r[1]) for r in rows)
        blitz_width = max(len(r[2]) for r in rows)
        rapid_width = max(len(r[3]) for r in rows)

        return "\n".join(
            f"{username:<{name_width}}  "
            f"⚡{bullet:>{bullet_width}} 🔥{blitz:>{blitz_width}} 🐇{rapid:>{rapid_width}}"
            for username, bullet, blitz, rapid in rows
        )

    @staticmethod
    def format_last_year_or_1000(data: Dict[str, Any], username: str, lang: str = 'en') -> str:
        """
        /year: last year or last 1000 rated games (a GamesOfPeriodResponse-like
        payload), HTML. Title with the dates, then three lines per mode:

            🔥 Blitz 2257 (+45)
               523 партии · +250 −230 =43
               точность 78 %

        (accuracy only for blitz/rapid/classical with analysed games). The old
        one-line-per-mode table was 48 characters wide and English in both
        languages; every line here is within 34 except the one with the name.
        """
        if not data:
            return t('no_data', lang)
        shown = html.escape(username)
        games_count = data.get('games_count', 0)
        period_start = data.get('period_start')
        period_end = data.get('period_end')
        stats = (data.get('data') or {})

        def day(ts) -> str:
            return datetime.fromtimestamp(ts).strftime("%d.%m.%Y") if isinstance(ts, int) else "—"

        if games_count >= 1000:
            header = t('year_title_1000', lang, name=shown, date=day(data.get('earliest_game_ts')))
        else:
            # Use earliest actual game date instead of naive 'year ago'
            header = t('year_title', lang, name=shown, games=format_count(games_count, 'games', lang),
                       start=day(data.get('earliest_game_ts', period_start)), end=day(period_end))

        blocks = []
        for mode in ["bullet", "blitz", "rapid", "classical", "correspondence"]:
            mode_stats = stats.get(mode)
            if not mode_stats or mode_stats.get('games_played', 0) == 0:
                continue
            lines = [
                StatsFormatter.format_mode_line(mode, mode_stats, lang, with_wins=False),
                t('year_mode_results', lang,
                  games=format_count(mode_stats.get('games_played', 0), 'games', lang),
                  wins=mode_stats.get('wins', 0), losses=mode_stats.get('losses', 0), draws=mode_stats.get('draws', 0)),
            ]
            if mode in ROW_MODES and mode_stats.get('accuracy') is not None:
                lines.append(t('year_mode_accuracy', lang, acc=StatsFormatter._format_accuracy(mode_stats['accuracy'])))
            blocks.append("\n".join(lines))

        if not blocks:
            return f"{header}\n\n{t('no_data', lang)}"
        return header + "\n\n" + "\n\n".join(blocks)