"""Forward messages to user or group — digianti-style forward system."""
from __future__ import annotations

import logging

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 forward_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """
    /forward <user_id> — Forward replied message to a user
    /forward <chat_id> <msg_id> — Forward a specific message
    """
    if not update.message or not update.message.text:
        return

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

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

    parts = update.message.text.split()
    if len(parts) < 2:
        await update.message.reply_text(
            "UsageId:\n"
            "/forward <user_id> — فوروارد پیام ریپلای به کاربر\n"
            "/forward <chat_id> <msg_id> — فوروارد پیام خاص"
        )
        return

    try:
        target_id = int(parts[1])
    except ValueError:
        await update.message.reply_text("شناسه باید عدد باشد.")
        return

    # If replying to a message, forward it
    if update.message.reply_to_message:
        try:
            await update.message.reply_to_message.forward(target_id)
            await update.message.reply_text(f"✅ پیام به {target_id} فوروارد شد.")
        except Exception as e:
            await update.message.reply_text(f"❌ خطا در فوروارد: {e}")
        return

    # If specific msg_id provided
    if len(parts) >= 3:
        try:
            msg_id = int(parts[2])
        except ValueError:
            await update.message.reply_text("message_id باید عدد باشد.")
            return

        try:
            await context.bot.forward_message(
                chat_id=target_id,
                from_chat_id=chat_id,
                message_id=msg_id,
            )
            await update.message.reply_text(f"✅ پیام به {target_id} فوروارد شد.")
        except Exception as e:
            await update.message.reply_text(f"❌ خطا در فوروارد: {e}")
        return

    await update.message.reply_text("لطفاً یک پیام را ریپلای کنید یا message_id وارد کنید.")


async def forward_user_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Forward a message to a specific user by username."""
    if not update.message or not update.message.text:
        return

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

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

    parts = update.message.text.split()
    if len(parts) < 2:
        await update.message.reply_text("UsageId:\n/fwd @username — فوروارد به کاربر")
        return

    username = parts[1].lstrip("@")
    if not update.message.reply_to_message:
        await update.message.reply_text("لطفاً یک پیام را ریپلای کنید.")
        return

    try:
        await update.message.reply_to_message.forward(f"@{username}")
        await update.message.reply_text(f"✅ پیام به @{username} فوروارد شد.")
    except Exception as e:
        await update.message.reply_text(f"❌ خطا: کاربر یافت نشد یا خصوصی است.\n{e}")


def register(app) -> None:
    from telegram.ext import CommandHandler
    app.add_handler(CommandHandler("forward", forward_cmd))
    app.add_handler(CommandHandler("fwd", forward_user_cmd))
