"""Chatbot Q&A — DB-driven answers with Persian normalization and fuzzy matching."""
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 import db
from bot.helpers import is_chat_admin

logger = logging.getLogger(__name__)


async def qa_set_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Set a Q&A pair: /qa set question | answer"""
    if not update.message or not update.message.text:
        return
    parts = update.message.text.split(None, 3)
    if len(parts) < 4:
        await update.message.reply_text(
            "UsageId:\n/qa set سوال | پاسخ\n\n"
            "مثال:\n/qa set سلام | سلام عزیزم"
        )
        return

    payload = parts[3]
    if "|" not in payload:
        await update.message.reply_text("از | بین سوال و پاسخ استفاده کنید.")
        return

    question, answer = payload.split("|", 1)
    question = question.strip()
    answer = answer.strip()

    if not question or not answer:
        await update.message.reply_text("سوال و پاسخ نمی‌توانند خالی باشند.")
        return

    chat_id = update.effective_chat.id
    user_id = update.effective_user.id

    if not await is_chat_admin(context.bot, chat_id, user_id):
        await update.message.reply_text("فقط ادمین‌ها می‌توانند Q&A تنظیم کنند.")
        return

    updated = await db.add_qa(chat_id, question, answer, created_by=user_id)
    if updated:
        await update.message.reply_text(f"✅ پاسخ سوال «{escape(question)}» بروزرسانی شد.")
    else:
        await update.message.reply_text(f"✅ پاسخ سوال «{escape(question)}» ذخیره شد.")


async def qa_del_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Delete a Q&A: /qa del question"""
    if not update.message or not update.message.text:
        return
    parts = update.message.text.split(None, 3)
    if len(parts) < 4:
        await update.message.reply_text("UsageId:\n/qa del سوال")
        return

    question = parts[3].strip()
    chat_id = update.effective_chat.id
    user_id = update.effective_user.id

    if not await is_chat_admin(context.bot, chat_id, user_id):
        await update.message.reply_text("فقط ادمین‌ها می‌توانند Q&A حذف کنند.")
        return

    count = await db.remove_qa(chat_id, question)
    if count:
        await update.message.reply_text(f"✅ پاسخ سوال «{escape(question)}» حذف شد.")
    else:
        await update.message.reply_text("این سوال یافت نشد.")


async def qa_clean_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Remove all Q&A: /qa clean"""
    chat_id = update.effective_chat.id
    user_id = update.effective_user.id

    if not await is_chat_admin(context.bot, chat_id, user_id):
        await update.message.reply_text("فقط ادمین‌ها می‌توانند لیست را پاک کنند.")
        return

    count = await db.remove_all_qa(chat_id)
    await update.message.reply_text(f"✅ همه پاسخ‌ها حذف شدند. ({count} مورد)")


async def qa_list_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """List Q&A: /qa list"""
    chat_id = update.effective_chat.id
    items = await db.list_qa(chat_id)

    if not items:
        await update.message.reply_text("هیچ پاسخی ذخیره نشده است.")
        return

    text = "📝 لیست پاسخ‌ها:\n\n"
    for i, item in enumerate(items[:50], 1):
        text += f"{i}. <b>{escape(item['question'])}</b>\n   → {escape(item['answer'])}\n\n"

    if len(items) > 50:
        text += f"... و {len(items) - 50} مورد دیگر"

    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def handle_qa_response(update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool:
    """Check if message matches a Q&A. Returns True if handled."""
    if not update.message or not update.message.text:
        return False

    chat_id = update.effective_chat.id
    text = update.message.text.strip()

    # Skip commands
    if text.startswith("/"):
        return False

    answer = await db.find_qa(chat_id, text)
    if answer:
        await update.message.reply_text(answer)
        return True

    return False


def register(app) -> None:
    from telegram.ext import CommandHandler
    app.add_handler(CommandHandler("qa", qa_set_cmd))
