"""Quick polls — create Telegram native polls in groups."""
from __future__ import annotations

import logging
from html import escape

from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import ContextTypes

from bot.decorators import admin_only
from bot.persian_router import register_mixed

logger = logging.getLogger(__name__)


@admin_only
async def poll_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Create a quick poll: /poll سوال؟ | گزینه۱ | گزینه۲ | گزینه۳"""
    text = update.message.text or ""
    parts = text.split(maxsplit=1)
    if len(parts) < 2 or "|" not in parts[1]:
        await update.message.reply_text(
            "❌ استفاده: <code>poll سوال؟ | گزینه۱ | گزینه۲ | گزینه۳</code>\n"
            "مثال: <code>نظرسنجی بهترین زبان؟ | پایتون | جاوا | جی‌اس</code>",
            parse_mode=ParseMode.HTML,
        )
        return
    args = parts[1]
    segments = [s.strip() for s in args.split("|")]
    if len(segments) < 2:
        await update.message.reply_text("❌ حداقل یه سوال + ۲ گزینه بده", parse_mode=ParseMode.HTML)
        return
    question = segments[0]
    options = segments[1:]
    if len(options) < 2:
        await update.message.reply_text("❌ حداقل ۲ گزینه بده", parse_mode=ParseMode.HTML)
        return
    if len(options) > 10:
        options = options[:10]
    try:
        await update.message.reply_poll(
            question=escape(question),
            options=[escape(opt) for opt in options],
            is_anonymous=False,
            allows_multiple_answers=False,
        )
    except Exception as e:
        await update.message.reply_text(f"❌ خطا: {e}", parse_mode=ParseMode.HTML)


def register(app):
    register_mixed(
        app,
        {"poll": poll_cmd, "survey": poll_cmd},
        {"نظرسنجی": poll_cmd, "نظر سنجی": poll_cmd, "رای‌گیری": poll_cmd, "رای گیری": poll_cmd},
    )
