import logging
import json
import os
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Updater,
    CommandHandler,
    MessageHandler,
    ConversationHandler,
    CallbackQueryHandler,
    Filters,
)

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO,
)
logger = logging.getLogger(__name__)

BOT_TOKEN = os.environ.get(
    "BOT_TOKEN",
    "8015794574:AAGDruWoNIMpvkF2eAhIVvt_1pyFPkuc3zU",
)
CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")

ALIAS, POST = range(2)
user_data = {}
pending_posts = {}
_post_id_counter = 0


def load_config():
    try:
        if os.path.exists(CONFIG_PATH):
            with open(CONFIG_PATH, "r", encoding="utf-8") as f:
                return json.load(f)
    except Exception as e:
        logger.error(f"Error loading config: {e}")
    return {"admin_id": 989586985, "channel_id": "@ketabbase"}


def save_config(config):
    try:
        with open(CONFIG_PATH, "w", encoding="utf-8") as f:
            json.dump(config, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        logger.error(f"Error saving config: {e}")
        return False


def get_admin_id(context):
    if context and context.bot_data.get("config"):
        return context.bot_data["config"].get("admin_id", 5726231978)
    return load_config().get("admin_id", 5726231978)


def get_channel_id(context):
    if context and context.bot_data.get("config"):
        return context.bot_data["config"].get("channel_id", "-1312418157")
    return load_config().get("channel_id", "-1312418157")


def start(update, context):
    user = update.effective_user
    update.message.reply_text(
        f"سلام {user.first_name}! 👋\n\n"
        "من به شما کمک می‌کنم تا یک پست ارسال کنید.\n\n"
        "لطفاً نام مستعار خود را وارد کنید:"
    )
    return ALIAS


def get_alias(update, context):
    user_id = update.effective_user.id
    alias = update.message.text
    if user_id not in user_data:
        user_data[user_id] = {}
    user_data[user_id]["alias"] = alias
    update.message.reply_text(
        "عالی! ✅\n\n" "حالا لطفاً محتوای پست خود را بنویسید:"
    )
    return POST


def get_post(update, context):
    user_id = update.effective_user.id
    post_content = update.message.text
    alias = user_data.get(user_id, {}).get("alias", "نامشخص")

    post_text = f"📝 {post_content}\n\n👤 {alias}\n\n🔗 @ketabbase \n🤖 ارسال‌شده توسط\n 🔗 @ketabbase_bot\n"

    global _post_id_counter
    _post_id_counter += 1
    post_id = _post_id_counter
    pending_posts[post_id] = {"alias": alias, "content": post_content, "full_text": post_text}

    admin_id = get_admin_id(context)
    keyboard = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton("✅ تایید و ارسال به کانال", callback_data=f"approve_{post_id}"),
                InlineKeyboardButton("❌ رد", callback_data=f"reject_{post_id}"),
            ]
        ]
    )

    try:
        context.bot.send_message(
            chat_id=admin_id,
            text="📬 پست جدید در انتظار تایید:\n\n" + post_text,
            reply_markup=keyboard,
        )
        update.message.reply_text(
            "✅ پست شما ارسال شد!\n\n"
            "پست به مدیر ارسال شده و پس از تایید در کانال منتشر می‌شود."
        )
        if user_id in user_data:
            del user_data[user_id]
    except Exception as e:
        logger.error(f"Error sending message to admin: {e}")
        del pending_posts[post_id]
        update.message.reply_text(
            "❌ متأسفانه خطایی در ارسال پست شما رخ داد.\n" "لطفاً بعداً دوباره تلاش کنید."
        )
    return ConversationHandler.END


def button_callback(update, context):
    query = update.callback_query
    admin_id = get_admin_id(context)
    if query.from_user.id != admin_id:
        query.answer("فقط مدیر می‌تواند تایید یا رد کند.", show_alert=True)
        return
    query.answer()

    data = query.data
    if not data.startswith("approve_") and not data.startswith("reject_"):
        return
    try:
        post_id = int(data.split("_")[1])
    except (IndexError, ValueError):
        return

    post = pending_posts.pop(post_id, None)
    if not post:
        query.edit_message_text(
            text=query.message.text + "\n\n⚠️ این پست قبلاً پردازش شده است."
        )
        return

    if data.startswith("approve_"):
        channel_id = get_channel_id(context)
        try:
            context.bot.send_message(chat_id=channel_id, text=post["full_text"])
            query.edit_message_text(
                text=query.message.text + "\n\n✅ تایید شده و در کانال منتشر شد."
            )
        except Exception as e:
            logger.error(f"Error sending to channel: {e}")
            pending_posts[post_id] = post
            query.edit_message_text(
                text=query.message.text + f"\n\n❌ خطا در ارسال به کانال: {str(e)}"
            )
    else:
        query.edit_message_text(text=query.message.text + "\n\n❌ رد شده.")


def cmd_setadmin(update, context):
    user_id = update.effective_user.id
    admin_id = get_admin_id(context)
    if user_id != admin_id:
        update.message.reply_text("⛔ فقط مدیر فعلی می‌تواند مدیر جدید تنظیم کند.")
        return
    if not context.args or len(context.args) != 1:
        update.message.reply_text(
            "استفاده: /setadmin <شناسه عددی کاربر>\n\n"
            "مثال: /setadmin 123456789\n\n"
            "برای پیدا کردن شناسه کاربر، از ربات @userinfobot در تلگرام استفاده کنید."
        )
        return
    try:
        new_admin_id = int(context.args[0])
    except ValueError:
        update.message.reply_text("❌ شناسه مدیر باید یک عدد باشد.")
        return
    config = load_config()
    config["admin_id"] = new_admin_id
    if save_config(config):
        if context.bot_data.get("config") is None:
            context.bot_data["config"] = {}
        context.bot_data["config"]["admin_id"] = new_admin_id
        update.message.reply_text(
            f"✅ مدیر با موفقیت تغییر کرد.\nشناسه مدیر جدید: {new_admin_id}"
        )
    else:
        update.message.reply_text("❌ خطا در ذخیره تنظیمات.")


def cmd_setchannel(update, context):
    user_id = update.effective_user.id
    if user_id != get_admin_id(context):
        update.message.reply_text("⛔ فقط مدیر می‌تواند کانال را تنظیم کند.")
        return
    if not context.args or len(context.args) != 1:
        update.message.reply_text(
            "استفاده: /setchannel <شناسه کانال یا @username>\n\n"
            "مثال: /setchannel -1001312418157 یا /setchannel @ketabbase\n"
            "یا: /setchannel @birjand_uni_twitter"
        )
        return
    channel = context.args[0].strip()
    config = load_config()
    config["channel_id"] = channel
    if save_config(config):
        if context.bot_data.get("config") is None:
            context.bot_data["config"] = {}
        context.bot_data["config"]["channel_id"] = channel
        update.message.reply_text(f"✅ کانال تنظیم شد: {channel}")
    else:
        update.message.reply_text("❌ خطا در ذخیره تنظیمات.")


def cancel(update, context):
    user_id = update.effective_user.id
    if user_id in user_data:
        del user_data[user_id]
    update.message.reply_text(
        "عملیات لغو شد. برای شروع مجدد از /start استفاده کنید."
    )
    return ConversationHandler.END


def error_handler(update, context):
    logger.error(f"Update {update} caused error {context.error}")
    if update and update.effective_message:
        update.effective_message.reply_text(
            "خطایی رخ داد. لطفاً دوباره تلاش کنید یا از /start برای شروع مجدد استفاده کنید."
        )


def main():
    config = load_config()
    updater = Updater(BOT_TOKEN, use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.bot_data["config"] = config

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler("start", start)],
        states={
            ALIAS: [MessageHandler(Filters.text & ~Filters.command, get_alias)],
            POST: [MessageHandler(Filters.text & ~Filters.command, get_post)],
        },
        fallbacks=[CommandHandler("cancel", cancel)],
    )
    dispatcher.add_handler(conv_handler)
    dispatcher.add_handler(CallbackQueryHandler(button_callback))
    dispatcher.add_handler(CommandHandler("setadmin", cmd_setadmin))
    dispatcher.add_handler(CommandHandler("setchannel", cmd_setchannel))
    dispatcher.add_error_handler(error_handler)

    logger.info("ربات در حال راه‌اندازی است...")
    updater.start_polling()
    updater.idle()


if __name__ == "__main__":
    main()
