"""Sticker panel helper — sends a themed sticker before panel responses."""
from __future__ import annotations

import logging
import random

from telegram import Update
from telegram.ext import ContextTypes

logger = logging.getLogger(__name__)

# Standard separator for all panels
SEPARATOR = "━" * 22

# Management-themed sticker file_ids (set after first successful send)
_cached_stickers: dict[str, str] = {}

# Fallback: well-known Telegram management sticker packs
_STICKER_PACKS = [
    "BokBloks",
    "BOTzzz",
    "BKbWink",
    "Xullurdzlozydfuz",
    "BlaBlaBla",
]


async def _find_mgmt_sticker(context: ContextTypes.DEFAULT_TYPE) -> str | None:
    """Try to find a management-themed sticker from known packs."""
    for pack in _STICKER_PACKS:
        try:
            sticker_set = await context.bot.get_sticker_set(pack)
            if sticker_set and sticker_set.stickers:
                sticker = random.choice(sticker_set.stickers)
                return sticker.file_id
        except Exception:
            continue
    return None


async def send_panel_sticker(
    update: Update,
    context: ContextTypes.DEFAULT_TYPE,
    force: bool = False,
) -> bool:
    """Send a random management-themed sticker before a panel.

    Returns True if sticker was sent, False otherwise.
    Sends ~40% of the time unless force=True.
    """
    if not force and random.random() > 0.4:
        return False

    chat_id = update.effective_chat.id
    if not chat_id:
        return False

    # Try cached first
    if _cached_stickers:
        fid = random.choice(list(_cached_stickers.values()))
        try:
            await context.bot.send_sticker(chat_id, fid)
            return True
        except Exception:
            pass

    # Try to find a sticker
    fid = await _find_mgmt_sticker(context)
    if fid:
        cache_key = f"mgmt_{len(_cached_stickers)}"
        _cached_stickers[cache_key] = fid
        try:
            await context.bot.send_sticker(chat_id, fid)
            return True
        except Exception:
            pass

    return False


def get_panel_header(emoji: str, title: str, subtitle: str = "") -> str:
    """Build a consistent panel header with decorative separators."""
    lines = [
        f"{emoji} <b>{title}</b>",
    ]
    if subtitle:
        lines.append(f"<i>{subtitle}</i>")
    lines.append(SEPARATOR)
    return "\n".join(lines)


def section_line(label: str, value: str, emoji: str = "•") -> str:
    return f"{emoji} <b>{label}:</b> {value}"


def status_dot(enabled: bool) -> str:
    return "✅" if enabled else "❌"


def lock_emoji(is_locked: bool) -> str:
    return "🔒" if is_locked else "🔓"
