import json
import os
import asyncio
from dotenv import load_dotenv
from telethon import TelegramClient, events
from telegram.ext import Application, CommandHandler, ContextTypes
from telegram import Update

# --- ۱. خواندن اطلاعات از فایل .env ---
load_dotenv()
API_ID = int(os.getenv("API_ID"))
API_HASH = os.getenv("API_HASH")
BOT_TOKEN = os.getenv("BOT_TOKEN")
PHONE_NUMBER = os.getenv("PHONE_NUMBER")

CONFIG_FILE = "config.json"

# --- ۲. توابع ساده برای خواندن و ذخیره تنظیمات ---
def load_config():
    with open(CONFIG_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_config(config):
    with open(CONFIG_FILE, "w", encoding="utf-8") as f:
        json.dump(config, f, ensure_ascii=False, indent=4)

# --- ۳. دستورات ربات (برای مدیریت دستی از داخل تلگرام) ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "سلام! من ربات انتقال اخبار هستم.\n"
        "دستورات:\n"
        "/add_source @channel - افزودن کانال مبدا\n"
        "/add_dest @channel - افزودن کانال مقصد\n"
        "/add_filter کلمه - افزودن کلمه ممنوعه\n"
        "/set_footer متن - تنظیم قالب پایین پست\n"
        "/status - مشاهده تنظیمات فعلی"
    )

async def add_source(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args: return await update.message.reply_text("آیدی کانال را وارد کنید.")
    config = load_config()
    channel = context.args[0]
    if channel not in config["source_channels"]:
        config["source_channels"].append(channel)
        save_config(config)
        await update.message.reply_text(f"کانال مبدا {channel} اضافه شد.")
    else:
        await update.message.reply_text("این کانال قبلاً اضافه شده بود.")

async def add_dest(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args: return await update.message.reply_text("آیدی کانال را وارد کنید.")
    config = load_config()
    channel = context.args[0]
    if channel not in config["destination_channels"]:
        config["destination_channels"].append(channel)
        save_config(config)
        await update.message.reply_text(f"کانال مقصد {channel} اضافه شد.")
    else:
        await update.message.reply_text("این کانال قبلاً اضافه شده بود.")

async def add_filter(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args: return await update.message.reply_text("کلمه را وارد کنید.")
    config = load_config()
    word = " ".join(context.args)
    if word not in config["forbidden_words"]:
        config["forbidden_words"].append(word)
        save_config(config)
        await update.message.reply_text(f"کلمه ممنوعه '{word}' اضافه شد.")
    else:
        await update.message.reply_text("این کلمه قبلاً اضافه شده بود.")

async def set_footer(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args: return await update.message.reply_text("متن قالب را وارد کنید.")
    config = load_config()
    config["custom_footer"] = " ".join(context.args).replace("\\n", "\n")
    save_config(config)
    await update.message.reply_text("قالب پایین پست تنظیم شد.")

async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
    config = load_config()
    text = f"📡 کانال‌های مبدا: {', '.join(config['source_channels'])}\n"
    text += f"🎯 کانال‌های مقصد: {', '.join(config['destination_channels'])}\n"
    text += f"🚫 کلمات ممنوعه: {', '.join(config['forbidden_words'])}"
    await update.message.reply_text(text)

# --- ۴. بخش اصلی: اتصال به تلگرام و گوش دادن به کانال‌ها ---
user_client = TelegramClient("userbot_session", API_ID, API_HASH)

async def main():
    # راه‌اندازی ربات (برای دستورات)
    app = Application.builder().token(BOT_TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("add_source", add_source))
    app.add_handler(CommandHandler("add_dest", add_dest))
    app.add_handler(CommandHandler("add_filter", add_filter))
    app.add_handler(CommandHandler("set_footer", set_footer))
    app.add_handler(CommandHandler("status", status))
    
    await app.initialize()
    await app.start()
    await app.updater.start_polling()

    # راه‌اندازی اکانت کاربری (برای خواندن کانال‌ها)
    print("در حال اتصال به تلگرام...")
    await user_client.start(phone=PHONE_NUMBER)
    print("اتصال برقرار شد!")
    
    # هندلر (شنونده) پیام‌های جدید
    @user_client.on(events.NewMessage(chats=load_config()["source_channels"]))
    async def handler(event):
        cfg = load_config()
        message_text = event.message.message or ""
        
        # فیلتر کلمات ممنوعه
        for word in cfg["forbidden_words"]:
            if word in message_text:
                print(f"پست به دلیل کلمه '{word}' ارسال نشد.")
                return

        # اضافه کردن قالب
        new_text = message_text + cfg["custom_footer"]
        
        # ارسال به کانال‌های مقصد
        for dest in cfg["destination_channels"]:
            try:
                await app.bot.send_message(chat_id=dest, text=new_text)
                print(f"پست به {dest} ارسال شد.")
            except Exception as e:
                print(f"خطا در ارسال به {dest}: {e}")

    print("ربات آماده است. در حال گوش دادن به کانال‌ها...")
    await user_client.run_until_disconnected()
    await app.updater.stop()
    await app.stop()

if __name__ == "__main__":
    asyncio.run(main())