"""Admin notes — save private notes about users visible to all admins."""
from __future__ import annotations

import logging

from telegram import Update
from telegram.ext import ContextTypes

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

logger = logging.getLogger(__name__)


async def _parse_target(update: Update) -> tuple[int | None, str | None]:
    """Extract target user and note text from message."""
    text = update.message.text or ""
    parts = text.split(maxsplit=2)
    target: int | None = None
    note_text: str | None = None

    if update.message.reply_to_message:
        target = update.message.reply_to_message.from_user.id
        note_text = parts[-1] if len(parts) >= 2 else None
        return target, note_text

    if len(parts) >= 2:
        from bot.helpers import extract_user
        target = await extract_user(update, parts[1])
        if not target:
            return None, None
        note_text = parts[2] if len(parts) >= 3 else None
    return target, note_text


@admin_only
async def note_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Save a note about a user."""
    chat = update.effective_chat
    target, note_text = await _parse_target(update)
    if not target:
        await update.message.reply_text("❌ روی کاربر ریپلای کن یا یوزرنیم/آیدی بده")
        return
    if not note_text:
        row = await db.get_admin_note(chat.id, target)
        if row:
            await update.message.reply_text(
                f"📝 <b>یادداشت مدیر</b> <code>{target}</code>\n\n{row['note']}",
                parse_mode="HTML",
            )
        else:
            await update.message.reply_text(f"📝 یادداشتی برای <code>{target}</code> نیست", parse_mode="HTML")
        return
    await db.set_admin_note(chat.id, target, note_text, update.effective_user.id)
    await update.message.reply_text(f"✅ یادداشت برای <code>{target}</code> ذخیره شد", parse_mode="HTML")


@admin_only
async def delnote_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Delete a user note."""
    chat = update.effective_chat
    target, _ = await _parse_target(update)
    if not target:
        await update.message.reply_text("❌ روی کاربر ریپلای کن یا یوزرنیم/آیدی بده")
        return
    await db.delete_admin_note(chat.id, target)
    await update.message.reply_text(f"✅ یادداشت <code>{target}</code> حذف شد", parse_mode="HTML")


@admin_only
async def noteslist_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """List all users with notes."""
    chat = update.effective_chat
    rows = await db.list_admin_notes(chat.id)
    if not rows:
        await update.message.reply_text("📝 هیچ یادداشتی وجود نداره")
        return
    lines = [f"📝 <b>یادداشت‌های مدیران ({len(rows)})</b>\n"]
    for r in rows[:20]:
        lines.append(f"• <code>{r['user_id']}</code>: {r['note'][:60]}")
    await update.message.reply_text("\n".join(lines), parse_mode="HTML")


def register(app):
    register_mixed(
        app,
        {"note": note_cmd, "delnote": delnote_cmd, "noteslist": noteslist_cmd},
        {
            "یادداشت مدیر": note_cmd,
            "یادداشت کاربر": note_cmd,
            "یادداشت": note_cmd,
            "حذف یادداشت مدیر": delnote_cmd,
            "حذف یادداشت کاربر": delnote_cmd,
            "لیست یادداشت مدیران": noteslist_cmd,
            "یادداشت‌های مدیران": noteslist_cmd,
        },
    )
