"""Auto-forward audio/music from channels to a group."""
from __future__ import annotations

import logging

from telegram import Update
from telegram.ext import ContextTypes, MessageHandler, filters

from bot import db
from bot.config import CHANNEL_FORWARD_TARGET

logger = logging.getLogger(__name__)


async def _get_source_channel_ids() -> list[int]:
    """Get all source channel IDs that have auto-forward enabled."""
    raw = await db.get_setting(-1, "channel_forward_sources", "")
    if not raw:
        return []
    return [int(x) for x in raw.split(",") if x.strip()]


async def _add_source_channel(channel_id: int) -> None:
    ids = await _get_source_channel_ids()
    if channel_id not in ids:
        ids.append(channel_id)
        await db.set_setting(-1, "channel_forward_sources", ",".join(str(i) for i in ids))


async def _remove_source_channel(channel_id: int) -> None:
    ids = await _get_source_channel_ids()
    if channel_id in ids:
        ids.remove(channel_id)
        await db.set_setting(-1, "channel_forward_sources", ",".join(str(i) for i in ids))


async def _get_target_group() -> int:
    val = await db.get_setting(-1, "channel_forward_target", CHANNEL_FORWARD_TARGET)
    return int(val)


async def _set_target_group(chat_id: int) -> None:
    await db.set_setting(-1, "channel_forward_target", str(chat_id))


async def channel_post_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """When a channel posts a message, check if it's a source and forward audio."""
    post = update.channel_post
    if not post or not post.audio:
        return

    source_channels = await _get_source_channel_ids()
    if post.chat_id not in source_channels:
        return

    target = await _get_target_group()
    try:
        await post.forward(target)
        logger.info("Forwarded audio from channel %s to %s", post.chat_id, target)
    except Exception as e:
        logger.warning("Failed to forward audio: %s", e)


async def set_source_channel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Set this channel as a source for audio forwarding.
    
    Usage: send this command in the source channel.
    """
    chat = update.effective_chat
    if not chat or chat.type != "channel":
        await update.effective_message.reply_text("❌ این دستور فقط در کانال کار می‌کند.")
        return
    await _add_source_channel(chat.id)
    await update.effective_message.reply_text(
        f"✅ کانال `{chat.title}` به عنوان منبع موزیک تنظیم شد.\n"
        "از این به بعد هر آهنگی بذاره به گروه مقصد فوروارد میشه.",
        parse_mode="Markdown",
    )
    logger.info("Source channel set: %s (%d)", chat.title, chat.id)


async def remove_source_channel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Remove this channel from forwarding sources."""
    chat = update.effective_chat
    if not chat or chat.type != "channel":
        await update.effective_message.reply_text("❌ این دستور فقط در کانال کار می‌کند.")
        return
    await _remove_source_channel(chat.id)
    await update.effective_message.reply_text(
        f"✅ کانال `{chat.title}` از لیست منابع حذف شد.",
        parse_mode="Markdown",
    )


async def set_forward_target(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Set this group as the forwarding target."""
    chat = update.effective_chat
    if not chat or chat.type not in ("group", "supergroup"):
        await update.effective_message.reply_text("❌ این دستور فقط در گروه کار می‌کند.")
        return
    await _set_target_group(chat.id)
    await update.effective_message.reply_text(
        f"✅ این گروه (`{chat.title}`) به عنوان مقصد فوروارد موزیک تنظیم شد.",
        parse_mode="Markdown",
    )


async def list_sources(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Show configured source channels and target group."""
    sources = await _get_source_channel_ids()
    target = await _get_target_group()
    lines = ["📡 **تنظیمات فوروارد موزیک**\n"]
    if sources:
        for cid in sources:
            try:
                chat = await context.bot.get_chat(cid)
                name = chat.title or str(cid)
            except Exception:
                name = str(cid)
            lines.append(f"  📥 کانال منبع: `{name}` (`{cid}`)")
    else:
        lines.append("  ❌ هیچ کانالی تنظیم نشده.")
    lines.append(f"  📤 گروه مقصد: `{target}`")
    await update.effective_message.reply_text("\n".join(lines), parse_mode="Markdown")


def register(app) -> None:
    from bot.persian_router import register_mixed

    app.add_handler(MessageHandler(filters.UpdateType.CHANNEL_POST, channel_post_handler))
    register_mixed(
        app,
        {
            "setmusicchannel": set_source_channel,
            "removemusicchannel": remove_source_channel,
            "setmusicgroup": set_forward_target,
            "musicstatus": list_sources,
        },
        {
            "تنظیم کانال موزیک": set_source_channel,
            "حذف کانال موزیک": remove_source_channel,
            "تنظیم گروه موزیک": set_forward_target,
            "وضعیت موزیک": list_sources,
        },
    )
    logger.info("Channel forward handler registered")
