from __future__ import annotations

import html

from .stats import format_duration


def _e(value) -> str:
    return html.escape(str(value), quote=False)


def already_running(minutes: int) -> str:
    return f"<b>Už hráš</b> {_e(minutes)} min."


def already_running_elsewhere(since_str: str, chat_id: int) -> str:
    return (
        f"Už máš spustenú reláciu inde (chat: <code>{_e(chat_id)}</code>) od {_e(since_str)}. "
        "Najprv ju ukonči <code>/end</code>."
    )


def hours_word(hours: int) -> str:
    if hours == 1:
        return "hodinu"
    if 2 <= hours <= 4:
        return "hodiny"
    return "hodín"


def reminder_hours(name: str, hours: int) -> str:
    return f"❗️❗️❗️ <b>Upozornenie:</b> {_e(name)} hrá už {_e(hours)} {hours_word(hours)}."


def reminder_minutes(name: str, minutes: int) -> str:
    return f"❗️❗️❗️ <b>Upozornenie:</b> {_e(name)} hrá už {_e(minutes)} min."


def started(now_str: str, task_name: str | None = None) -> str:
    if task_name:
        return f"🟢 <b>Štartujem meranie:</b> {_e(task_name)}. ({_e(now_str)})"
    return f"🟢 <b>Štartujem meranie.</b> ({_e(now_str)})"


def stopped(session_hhmm: str, today_total: str, task_name: str | None = None) -> str:
    if task_name:
        return (
            f"✅ <b>Ukončené</b> ({_e(task_name)}). Relácia: <code>{_e(session_hhmm)}</code>. "
            f"Dnes spolu: <code>{_e(today_total)}</code>."
        )
    return f"✅ <b>Ukončené.</b> Relácia: <code>{_e(session_hhmm)}</code>. Dnes spolu: <code>{_e(today_total)}</code>."


def no_active() -> str:
    return "⚪️ Nemáš spustené meranie."


def status_active(hhmm: str, since_str: str, task_name: str | None = None) -> str:
    if task_name:
        return (
            f"🟢 <b>Aktuálne hráš</b> <code>{_e(hhmm)}</code> (od {_e(since_str)}) — {_e(task_name)}."
        )
    return f"🟢 <b>Aktuálne hráš</b> <code>{_e(hhmm)}</code> (od {_e(since_str)})."


def status_inactive() -> str:
    return "⚪️ Teraz nemáš spustené meranie."


def status_admin_empty() -> str:
    return "Aktuálne nikto nehrá."


def status_admin_header() -> str:
    return "🟢 <b>Aktívne relácie:</b>"


def status_admin_line(name: str, hhmm: str, since_str: str) -> str:
    return f"• {_e(name)}: <code>{_e(hhmm)}</code> (od {_e(since_str)})"


def stats_report(
    today_sec: int,
    week_sec: int,
    month_sec: int,
    count: int,
    avg_sec: int,
) -> str:
    return (
        "📊 <b>Dnes:</b> <code>"
        + _e(format_duration(today_sec))
        + "</code>\n📊 <b>Posledných 7 dní:</b> <code>"
        + _e(format_duration(week_sec))
        + "</code>\n📊 <b>Tento mesiac:</b> <code>"
        + _e(format_duration(month_sec))
        + "</code>\n📌 <b>Počet relácií (range):</b> <code>"
        + _e(count)
        + "</code>\n📌 <b>Priemer relácie:</b> <code>"
        + _e(format_duration(avg_sec))
        + "</code>"
    )


def stats_admin_header(label: str) -> str:
    return f"📊 <b>Štatistiky skupiny</b> ({_e(label)}) – súčet naprieč chatmi:"


def stats_admin_line(rank: int, name: str, total_sec: int, sessions_count: int) -> str:
    avg = int(total_sec / sessions_count) if sessions_count else 0
    return (
        f"{_e(rank)}. {_e(name)} — <code>{_e(format_duration(total_sec))}</code> "
        f"(relácie: {_e(sessions_count)}, priemer: <code>{_e(format_duration(avg))}</code>)"
    )


def stats_admin_empty() -> str:
    return "⚠️ Žiadne dáta pre tento rozsah."


def stats_private_groups(top_groups: list[tuple[int, str]]) -> str:
    if not top_groups:
        return "⚠️ Top skupiny: (žiadne dáta)"
    lines = ["🏆 <b>Top skupiny:</b>"]
    for chat_id, total_hhmm in top_groups:
        lines.append(f"• <code>{_e(chat_id)}</code>: <code>{_e(total_hhmm)}</code>")
    return "\n".join(lines)


def leaderboard_header(label: str) -> str:
    return f"🏆 <b>Rebríček</b> ({_e(label)}):"


def leaderboard_line(rank: int, name: str, total_sec: int) -> str:
    trophy = " 🏆" if rank == 1 else ""
    return f"{_e(rank)}. {_e(name)}{trophy} — <code>{_e(format_duration(total_sec))}</code>"


def leaderboard_empty() -> str:
    return "⚠️ Žiadne dáta pre tento rozsah."


def tasks_header(label: str) -> str:
    return f"🧾 <b>Úlohy</b> ({_e(label)}):"


def tasks_line(rank: int, name: str, total_sec: int, sessions_count: int) -> str:
    return (
        f"{_e(rank)}. {_e(name)} — <code>{_e(format_duration(total_sec))}</code>"
        f" (relácie: {_e(sessions_count)})"
    )


def tasks_empty() -> str:
    return "⚠️ Žiadne úlohy pre tento rozsah."


def reminder(name: str) -> str:
    return f"❗️❗️❗️ <b>Upozornenie:</b> {_e(name)} hrá už 1 hodinu."


def private_top_unavailable() -> str:
    return "⚠️ Rebríček je dostupný len v skupine."


def invalid_range() -> str:
    return "⚠️ Neznámy rozsah. Použi: <code>today</code> | <code>7d</code> | <code>month</code>."


def menu_hint() -> str:
    return "ℹ️ Príkazy môžeš spúšťať aj tlačidlami nižšie."


def menu_hidden() -> str:
    return "ℹ️ Tlačidlá som skryl."


def admin_only() -> str:
    return "⚠️ Tento príkaz je len pre adminov skupiny."


def fix_usage() -> str:
    return "ℹ️ Použitie: <code>/fix &lt;id&gt; &lt;YYYY-MM-DD&gt; &lt;HH:MM&gt;</code> alebo <code>/fix &lt;id&gt; &lt;HH:MM&gt;</code> (dnes)"


def fix_not_found() -> str:
    return "⚠️ Relácia s týmto ID neexistuje."


def fix_wrong_chat() -> str:
    return "⚠️ Táto relácia nepatrí do tohto chatu."


def fix_already_done() -> str:
    return "⚠️ Táto relácia je už ukončená."


def fix_end_before_start() -> str:
    return "⚠️ Koniec musí byť neskôr ako začiatok relácie."


def fix_end_in_future() -> str:
    return "⚠️ Koniec nemôže byť v budúcnosti."


def fix_success(session_id: int, hhmm: str, duration_hhmm: str) -> str:
    return (
        f"✅ OK. Relácia <code>{_e(session_id)}</code> ukončená na {_e(hhmm)}. "
        f"Trvanie: <code>{_e(duration_hhmm)}</code>."
    )


def help_text() -> str:
    return (
        "ℹ️ <b>Príkazy:</b>\n"
        "<code>/start</code> – spustí meranie relácie\n"
        "<code>/end</code> – ukončí reláciu a uloží čas\n"
        "<code>/status</code> – zobrazí aktuálnu reláciu\n"
        "<code>/stats</code> [today|7d|month] – osobné štatistiky + rozpis týždňa (Po–Ne)\n"
        "<code>/top</code> [today|7d|month] – rebríček skupiny\n"
        "<code>/fix</code> &lt;id&gt; &lt;YYYY-MM-DD&gt; &lt;HH:MM&gt; – admin: ručné ukončenie relácie\n"
        "<code>/menu</code> – zobrazí tlačidlá\n"
        "<code>/hide</code> – skryje tlačidlá\n"
        "\n"
        "<b>Poznámky:</b>\n"
        "- V súkromnom chate /stats agreguje všetky skupiny.\n"
        "- V súkromnom chate /top ukáže úlohy zoradené podľa času.\n"
        "- V skupine admin bez parametra dostane týždeň (Po–Ne).\n"
        "- Vieš použiť aj <code>/stats chat:&lt;id&gt;</code>.\n"
        "- V súkromnom chate môžeš <code>/start &lt;názov úlohy&gt;</code>.\n"
    )
