import os
import zipfile

PROJECT_NAME = "stream-notifier-bot"
FILES = {}

# ============================================
# .env
# ============================================
FILES[".env"] = """# ========================================
# تنظیمات بات اطلاع‌رسانی استریم و ویدیو
# ========================================

# توکن بات تلگرام (از @BotFather تلگرام)
TELEGRAM_BOT_TOKEN=YOUR_TELEGRAM_BOT_TOKEN

# کلید API یوتیوب (از console.cloud.google.com)
YOUTUBE_API_KEY=YOUR_YOUTUBE_API_KEY

# آیدی عددی تلگرام ادمین (از @userinfobot)
ADMIN_TELEGRAM_ID=123456789

# توکن بات بله (از @botfather بله)
BALE_BOT_TOKEN=

# توکن روبیکا (اختیاری)
ROBIKA_BOT_TOKEN=
"""

# ============================================
# requirements.txt
# ============================================
FILES["requirements.txt"] = """python-telegram-bot==20.7
aiohttp==3.9.1
python-dotenv==1.0.0
apscheduler==3.10.4
aiosqlite==0.19.0
feedparser==6.0.11
"""

# ============================================
# database.py
# ============================================
FILES["database.py"] = r'''import aiosqlite
import os

DB_PATH = "bot_data.db"


async def init_db():
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("""
            CREATE TABLE IF NOT EXISTS settings (
                key TEXT PRIMARY KEY, value TEXT
            )
        """)
        await db.execute("""
            CREATE TABLE IF NOT EXISTS sent_videos (
                video_id TEXT PRIMARY KEY, platform TEXT,
                title TEXT, sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        await db.execute("""
            CREATE TABLE IF NOT EXISTS admins (
                user_id INTEGER PRIMARY KEY, name TEXT,
                added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        await db.commit()


async def get_setting(key, default=None):
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute("SELECT value FROM settings WHERE key=?", (key,))
        row = await cur.fetchone()
        return row[0] if row else default


async def set_setting(key, value):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute(
            "INSERT OR REPLACE INTO settings (key,value) VALUES (?,?)",
            (key, value)
        )
        await db.commit()


async def is_video_sent(video_id):
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute(
            "SELECT 1 FROM sent_videos WHERE video_id=?", (video_id,)
        )
        return await cur.fetchone() is not None


async def mark_video_sent(video_id, platform, title):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute(
            "INSERT OR IGNORE INTO sent_videos (video_id,platform,title) VALUES (?,?,?)",
            (video_id, platform, title)
        )
        await db.commit()


async def is_admin(user_id):
    admin_id = int(os.getenv("ADMIN_TELEGRAM_ID", "0"))
    if user_id == admin_id:
        return True
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute(
            "SELECT 1 FROM admins WHERE user_id=?", (user_id,)
        )
        return await cur.fetchone() is not None


async def add_admin(user_id, name):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute(
            "INSERT OR IGNORE INTO admins (user_id,name) VALUES (?,?)",
            (user_id, name)
        )
        await db.commit()


async def remove_admin(user_id):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("DELETE FROM admins WHERE user_id=?", (user_id,))
        await db.commit()


async def get_all_settings():
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute("SELECT key,value FROM settings")
        return {r[0]: r[1] for r in await cur.fetchall()}
'''

# ============================================
# youtube_checker.py
# ============================================
FILES["youtube_checker.py"] = r'''import aiohttp, os, logging
from datetime import datetime, timedelta
from database import get_setting, is_video_sent

logger = logging.getLogger(__name__)


class YouTubeChecker:
    def __init__(self):
        self.api_key = os.getenv("YOUTUBE_API_KEY")
        self.base = "https://www.googleapis.com/youtube/v3"

    async def check_new_videos(self):
        cid = await get_setting("youtube_channel_id")
        if not cid:
            return []
        out = []
        try:
            url = f"{self.base}/search"
            params = {
                "part": "snippet", "channelId": cid, "order": "date",
                "maxResults": 5, "type": "video", "key": self.api_key,
                "publishedAfter": (datetime.utcnow() - timedelta(hours=2)
                                   ).strftime("%Y-%m-%dT%H:%M:%SZ")
            }
            async with aiohttp.ClientSession() as s:
                async with s.get(url, params=params) as r:
                    if r.status == 200:
                        data = await r.json()
                        for it in data.get("items", []):
                            vid = it["id"]["videoId"]
                            if not await is_video_sent(vid):
                                out.append({
                                    "id": vid,
                                    "title": it["snippet"]["title"],
                                    "description": it["snippet"]["description"][:200],
                                    "thumbnail": it["snippet"]["thumbnails"]["high"]["url"],
                                    "url": f"https://youtube.com/watch?v={vid}",
                                    "type": "video"
                                })
        except Exception as e:
            logger.error(f"خطا یوتیوب: {e}")
        return out

    async def check_live_streams(self):
        cid = await get_setting("youtube_channel_id")
        if not cid:
            return []
        out = []
        try:
            url = f"{self.base}/search"
            params = {
                "part": "snippet", "channelId": cid,
                "eventType": "live", "type": "video",
                "key": self.api_key, "maxResults": 5
            }
            async with aiohttp.ClientSession() as s:
                async with s.get(url, params=params) as r:
                    if r.status == 200:
                        data = await r.json()
                        for it in data.get("items", []):
                            vid = it["id"]["videoId"]
                            sid = f"live_{vid}"
                            if not await is_video_sent(sid):
                                out.append({
                                    "id": sid,
                                    "title": it["snippet"]["title"],
                                    "description": it["snippet"]["description"][:200],
                                    "thumbnail": it["snippet"]["thumbnails"]["high"]["url"],
                                    "url": f"https://youtube.com/watch?v={vid}",
                                    "type": "live"
                                })
        except Exception as e:
            logger.error(f"خطا استریم: {e}")
        return out
'''

# ============================================
# aparat_checker.py
# ============================================
FILES["aparat_checker.py"] = r'''import aiohttp, logging, feedparser
from database import get_setting, is_video_sent

logger = logging.getLogger(__name__)


class AparatChecker:
    async def check_new_videos(self):
        username = await get_setting("aparat_username")
        if not username:
            return []
        out = []
        try:
            rss = f"https://www.aparat.com/rss/{username}"
            async with aiohttp.ClientSession() as s:
                async with s.get(rss) as r:
                    if r.status == 200:
                        feed = feedparser.parse(await r.text())
                        for e in feed.entries[:5]:
                            vid = f"aparat_{e.get('id', e.link)}"
                            if not await is_video_sent(vid):
                                out.append({
                                    "id": vid,
                                    "title": e.get("title", "بدون عنوان"),
                                    "description": e.get("summary", "")[:200],
                                    "thumbnail": "",
                                    "url": e.get("link", ""),
                                    "type": "video"
                                })
        except Exception as e:
            logger.error(f"خطا آپارات: {e}")
        return out
'''

# ============================================
# bale_bot.py  ←  ماژول جدید بله
# ============================================
FILES["bale_bot.py"] = r'''import aiohttp, logging
from database import get_setting

logger = logging.getLogger(__name__)

# API بله دقیقاً هم‌ساختار تلگرامه، فقط base URL فرق داره
BALE_API = "https://tapi.bale.ai"


class BaleNotifier:
    """ارسال پیام به کانال بله از طریق API رسمی بله"""

    async def send_notification(self, video_info: dict, platform: str) -> bool:
        token = await get_setting("bale_bot_token")
        channel = await get_setting("bale_channel_id")

        if not token or not channel:
            logger.debug("بله تنظیم نشده، رد شد")
            return False

        text = self._format(video_info, platform)
        url = f"{BALE_API}/bot{token}/sendMessage"

        payload = {
            "chat_id": channel,
            "text": text,
            "parse_mode": "HTML"
        }

        try:
            async with aiohttp.ClientSession() as s:
                # اول تلاش با عکس
                if video_info.get("thumbnail"):
                    photo_url = f"{BALE_API}/bot{token}/sendPhoto"
                    photo_payload = {
                        "chat_id": channel,
                        "photo": video_info["thumbnail"],
                        "caption": text,
                        "parse_mode": "HTML"
                    }
                    async with s.post(photo_url, json=photo_payload) as r:
                        if r.status == 200:
                            logger.info(f"✅ بله (عکس‌دار): {video_info['title']}")
                            return True

                # فقط متن
                async with s.post(url, json=payload) as r:
                    if r.status == 200:
                        logger.info(f"✅ بله: {video_info['title']}")
                        return True
                    else:
                        err = await r.text()
                        logger.error(f"خطا بله {r.status}: {err}")
                        return False
        except Exception as e:
            logger.error(f"خطا ارسال بله: {e}")
            return False

    async def send_custom_message(self, text: str) -> bool:
        """ارسال پیام دلخواه به کانال بله"""
        token = await get_setting("bale_bot_token")
        channel = await get_setting("bale_channel_id")
        if not token or not channel:
            return False
        url = f"{BALE_API}/bot{token}/sendMessage"
        try:
            async with aiohttp.ClientSession() as s:
                async with s.post(url, json={
                    "chat_id": channel, "text": text, "parse_mode": "HTML"
                }) as r:
                    return r.status == 200
        except:
            return False

    def _format(self, v: dict, platform: str) -> str:
        if platform == "youtube":
            emoji, name = "🔴", "YouTube"
        else:
            emoji, name = "🎬", "آپارات"

        if v.get("type") == "live":
            return (
                f"{emoji} <b>🔴 استریم زنده شروع شد!</b>\n\n"
                f"🎬 <b>{v['title']}</b>\n\n"
                f"📝 {v.get('description', '')}\n\n"
                f'🔗 <a href="{v["url"]}">لینک تماشا</a>\n\n'
                f"⏰ <b>همین الان شروع شده! بیاید ببینید</b> 🔥"
            )
        else:
            return (
                f"{emoji} <b>ویدیوی جدید در {name}!</b>\n\n"
                f"🎬 <b>{v['title']}</b>\n\n"
                f"📝 {v.get('description', '')}\n\n"
                f'🔗 <a href="{v["url"]}">لینک تماشا</a>\n\n'
                f"✨ <b>حتماً ببینید و نظرتون رو بگید!</b>"
            )
'''

# ============================================
# robika_bot.py
# ============================================
FILES["robika_bot.py"] = r'''import logging
from database import get_setting

logger = logging.getLogger(__name__)


class RobikaNotifier:
    def __init__(self):
        self.client = None
        self.is_connected = False

    async def initialize(self):
        try:
            from rubpy import Client
            auth = await get_setting("robika_auth")
            if not auth:
                logger.warning("توکن روبیکا تنظیم نشده")
                return False
            self.client = Client(session=auth)
            await self.client.start()
            self.is_connected = True
            logger.info("✅ اتصال روبیکا برقرار شد")
            return True
        except ImportError:
            logger.warning("rubpy نصب نیست. pip install rubpy")
            return False
        except Exception as e:
            logger.error(f"خطا روبیکا: {e}")
            return False

    async def send_notification(self, video_info, platform):
        guid = await get_setting("robika_channel_guid")
        if not guid or not self.is_connected:
            return False
        try:
            msg = self._fmt(video_info, platform)
            await self.client.send_message(object_guid=guid, text=msg)
            logger.info(f"✅ روبیکا: {video_info['title']}")
            return True
        except Exception as e:
            logger.error(f"خطا ارسال روبیکا: {e}")
            return False

    def _fmt(self, v, platform):
        emoji = "🔴" if platform == "youtube" else "🎬"
        name = "یوتیوب" if platform == "youtube" else "آپارات"
        if v.get("type") == "live":
            return (f"{emoji} استریم زنده در {name}!\n\n🎯 {v['title']}\n\n"
                    f"🔗 {v['url']}\n\n⏰ همین الان شروع شده! 🔥")
        return (f"{emoji} ویدیوی جدید در {name}!\n\n🎬 {v['title']}\n\n"
                f"🔗 {v['url']}\n\n✨ حتماً ببینید!")

    async def close(self):
        if self.client and self.is_connected:
            try:
                await self.client.disconnect()
            except:
                pass
'''

# ============================================
# telegram_bot.py  ←  آپدیت شده با بله
# ============================================
FILES["telegram_bot.py"] = r'''import os, logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Application, CommandHandler, CallbackQueryHandler,
    MessageHandler, filters, ContextTypes
)
from database import (
    is_admin, get_setting, set_setting,
    get_all_settings, add_admin
)

logger = logging.getLogger(__name__)


class TelegramBot:
    def __init__(self):
        self.token = os.getenv("TELEGRAM_BOT_TOKEN")
        self.app = None

    def create_app(self):
        self.app = Application.builder().token(self.token).build()
        self._register()
        return self.app

    def _register(self):
        self.app.add_handler(CommandHandler("start", self.cmd_start))
        self.app.add_handler(CommandHandler("panel", self.cmd_panel))
        self.app.add_handler(CommandHandler("status", self.cmd_status))
        self.app.add_handler(CommandHandler("help", self.cmd_help))
        self.app.add_handler(CommandHandler("test", self.cmd_test))
        self.app.add_handler(CommandHandler("cancel", self.cmd_cancel))
        self.app.add_handler(CallbackQueryHandler(self.on_button))
        self.app.add_handler(
            MessageHandler(filters.TEXT & ~filters.COMMAND, self.on_text)
        )

    # ──────── دستورات ────────

    async def cmd_start(self, u, c):
        user = u.effective_user
        if await is_admin(user.id):
            t = (
                f"سلام {user.first_name}! 👋\n\n"
                f"🤖 بات اطلاع‌رسانی استریم و ویدیو\n\n"
                f"✅ تو ادمین هستی!\n\n"
                f"📋 امکانات:\n"
                f"• ویدیو و استریم یوتیوب\n"
                f"• ویدیو آپارات\n"
                f"• ارسال به تلگرام 📢\n"
                f"• ارسال به بله 💬\n"
                f"• ارسال به روبیکا 📱\n\n"
                f"🔧 /panel  |  📊 /status"
            )
        else:
            t = f"سلام {user.first_name}! 👋\nفقط ادمین‌ها دسترسی دارند."
        await u.message.reply_text(t)

    async def cmd_panel(self, u, c):
        if not await is_admin(u.effective_user.id):
            await u.message.reply_text("⛔ دسترسی ندارید!")
            return
        kb = [
            [InlineKeyboardButton("📺 یوتیوب", callback_data="set_youtube"),
             InlineKeyboardButton("🎬 آپارات", callback_data="set_aparat")],
            [InlineKeyboardButton("📢 کانال تلگرام", callback_data="set_tg_ch"),
             InlineKeyboardButton("💬 کانال بله", callback_data="set_bale_ch")],
            [InlineKeyboardButton("📱 کانال روبیکا", callback_data="set_rb_ch"),
             InlineKeyboardButton("🔑 توکن بله", callback_data="set_bale_token")],
            [InlineKeyboardButton("🔑 توکن روبیکا", callback_data="set_rb_auth")],
            [InlineKeyboardButton("📊 وضعیت", callback_data="show_status"),
             InlineKeyboardButton("🧪 تست", callback_data="test_send")],
            [InlineKeyboardButton("👤 ادمین‌ها", callback_data="manage_admins"),
             InlineKeyboardButton("✉️ پیام دستی", callback_data="custom_msg")],
            [InlineKeyboardButton("✅ فعال/غیرفعال", callback_data="toggle"),
             InlineKeyboardButton("⏱ بازه چک", callback_data="set_interval")],
        ]
        await u.message.reply_text(
            "🔧 **پنل مدیریت**\n\nیک گزینه انتخاب کن:",
            reply_markup=InlineKeyboardMarkup(kb), parse_mode="Markdown"
        )

    async def cmd_status(self, u, c):
        if not await is_admin(u.effective_user.id):
            return
        s = await get_all_settings()
        on = s.get("is_active", "true") == "true"
        t = (
            f"📊 **وضعیت بات**\n\n"
            f"{'🟢' if on else '🔴'} {'فعال' if on else 'غیرفعال'}\n"
            f"⏱ هر {s.get('check_interval','120')} ثانیه\n\n"
            f"📺 یوتیوب: `{s.get('youtube_channel_id','❌')}`\n"
            f"🎬 آپارات: `{s.get('aparat_username','❌')}`\n\n"
            f"📢 تلگرام: `{s.get('telegram_channel_id','❌')}`\n"
            f"💬 بله: `{s.get('bale_channel_id','❌')}`\n"
            f"🔑 توکن بله: {'✅' if s.get('bale_bot_token') else '❌'}\n\n"
            f"📱 روبیکا: `{s.get('robika_channel_guid','❌')}`\n"
            f"🔑 توکن روبیکا: {'✅' if s.get('robika_auth') else '❌'}"
        )
        await u.message.reply_text(t, parse_mode="Markdown")

    async def cmd_help(self, u, c):
        await u.message.reply_text(
            "📖 **راهنما**\n\n"
            "/start - شروع\n/panel - پنل\n/status - وضعیت\n"
            "/test - تست\n/cancel - لغو\n\n"
            "1️⃣ یوتیوب و آپارات رو تنظیم کن\n"
            "2️⃣ کانال تلگرام، بله و روبیکا رو تنظیم کن\n"
            "3️⃣ بات رو ادمین کانال‌ها کن\n"
            "4️⃣ فعال کن!",
            parse_mode="Markdown"
        )

    async def cmd_test(self, u, c):
        if not await is_admin(u.effective_user.id):
            return
        v = {"id": "test", "title": "🧪 تست", "description": "پیام تست",
             "thumbnail": "", "url": "https://youtube.com", "type": "video"}
        r = await self.send_to_telegram(v, "youtube")
        await u.message.reply_text(f"📢 تلگرام: {'✅' if r else '❌'}")

    async def cmd_cancel(self, u, c):
        c.user_data.clear()
        await u.message.reply_text("❌ لغو شد.")

    # ──────── دکمه‌ها ────────

    async def on_button(self, u, c):
        q = u.callback_query
        await q.answer()
        if not await is_admin(q.from_user.id):
            await q.edit_message_text("⛔ دسترسی ندارید!")
            return
        d = q.data

        prompts = {
            "set_youtube": ("youtube_channel",
                "📺 آیدی کانال یوتیوب یا هندل رو بفرست:\n"
                "مثال: `UCxxxxx` یا `@channel`\n\n/cancel"),
            "set_aparat": ("aparat_username",
                "🎬 نام کاربری آپارات رو بفرست:\n"
                "مثال: `username`\n\n/cancel"),
            "set_tg_ch": ("telegram_channel",
                "📢 آیدی کانال تلگرام:\n"
                "مثال: `@mychannel` یا `-1001234567890`\n"
                "⚠️ بات باید ادمین باشه!\n\n/cancel"),
            "set_bale_ch": ("bale_channel",
                "💬 آیدی کانال بله رو بفرست:\n"
                "مثال: `@mychannel` یا آیدی عددی\n"
                "⚠️ بات بله باید ادمین کانال باشه!\n\n/cancel"),
            "set_bale_token": ("bale_token",
                "🔑 توکن بات بله رو بفرست:\n"
                "(از @botfather بله بگیر)\n\n/cancel"),
            "set_rb_ch": ("robika_channel",
                "📱 GUID کانال روبیکا رو بفرست:\n\n/cancel"),
            "set_rb_auth": ("robika_auth",
                "🔑 توکن روبیکا رو بفرست:\n\n/cancel"),
        }

        if d in prompts:
            key, msg = prompts[d]
            c.user_data["waiting_for"] = key
            await q.edit_message_text(msg, parse_mode="Markdown")

        elif d == "show_status":
            s = await get_all_settings()
            on = s.get("is_active", "true") == "true"
            t = (
                f"📊 **وضعیت:**\n{'🟢' if on else '🔴'} "
                f"{'فعال' if on else 'غیرفعال'}\n\n"
                f"📺 `{s.get('youtube_channel_id','❌')}`\n"
                f"🎬 `{s.get('aparat_username','❌')}`\n"
                f"📢 `{s.get('telegram_channel_id','❌')}`\n"
                f"💬 `{s.get('bale_channel_id','❌')}`\n"
                f"📱 `{s.get('robika_channel_guid','❌')}`"
            )
            await q.edit_message_text(t, parse_mode="Markdown",
                reply_markup=InlineKeyboardMarkup(
                    [[InlineKeyboardButton("🔙 برگشت", callback_data="back")]]))

        elif d == "test_send":
            await q.edit_message_text("🧪 در حال تست...")
            v = {"id": "t", "title": "🧪 تست", "description": "اگه میبینی درسته ✅",
                 "thumbnail": "", "url": "https://youtube.com", "type": "video"}
            r1 = await self.send_to_telegram(v, "youtube")

            # تست بله
            from bale_bot import BaleNotifier
            bale = BaleNotifier()
            r2 = await bale.send_notification(v, "youtube")

            await q.edit_message_text(
                f"🧪 **نتیجه تست:**\n\n"
                f"📢 تلگرام: {'✅' if r1 else '❌'}\n"
                f"💬 بله: {'✅' if r2 else '❌'}\n\n"
                f"💡 اگه ❌ هست، تنظیمات رو چک کن.")

        elif d == "toggle":
            cur = await get_setting("is_active", "true")
            nv = "false" if cur == "true" else "true"
            await set_setting("is_active", nv)
            st = "فعال ✅" if nv == "true" else "غیرفعال ❌"
            await q.edit_message_text(f"بات {st} شد!",
                reply_markup=InlineKeyboardMarkup(
                    [[InlineKeyboardButton("🔙 برگشت", callback_data="back")]]))

        elif d == "set_interval":
            kb = [
                [InlineKeyboardButton("30 ثانیه", callback_data="iv_30"),
                 InlineKeyboardButton("1 دقیقه", callback_data="iv_60")],
                [InlineKeyboardButton("2 دقیقه", callback_data="iv_120"),
                 InlineKeyboardButton("5 دقیقه", callback_data="iv_300")],
                [InlineKeyboardButton("10 دقیقه", callback_data="iv_600")],
                [InlineKeyboardButton("🔙 برگشت", callback_data="back")]
            ]
            await q.edit_message_text("⏱ بازه چک:",
                reply_markup=InlineKeyboardMarkup(kb))

        elif d.startswith("iv_"):
            sec = int(d.split("_")[1])
            await set_setting("check_interval", str(sec))
            await q.edit_message_text(f"✅ بازه: {sec} ثانیه")

        elif d == "manage_admins":
            c.user_data["waiting_for"] = "add_admin"
            await q.edit_message_text(
                "👤 آیدی عددی تلگرام ادمین جدید:\n(از @userinfobot)\n\n/cancel")

        elif d == "custom_msg":
            c.user_data["waiting_for"] = "custom_message"
            await q.edit_message_text(
                "✉️ متن پیام رو بنویس (به همه کانال‌ها ارسال میشه):\n\n/cancel")

        elif d == "back":
            await self._show_panel(q)

    async def _show_panel(self, q):
        kb = [
            [InlineKeyboardButton("📺 یوتیوب", callback_data="set_youtube"),
             InlineKeyboardButton("🎬 آپارات", callback_data="set_aparat")],
            [InlineKeyboardButton("📢 تلگرام", callback_data="set_tg_ch"),
             InlineKeyboardButton("💬 بله", callback_data="set_bale_ch")],
            [InlineKeyboardButton("📱 روبیکا", callback_data="set_rb_ch"),
             InlineKeyboardButton("🔑 توکن بله", callback_data="set_bale_token")],
            [InlineKeyboardButton("📊 وضعیت", callback_data="show_status"),
             InlineKeyboardButton("🧪 تست", callback_data="test_send")],
            [InlineKeyboardButton("✅ فعال/غیرفعال", callback_data="toggle"),
             InlineKeyboardButton("⏱ بازه", callback_data="set_interval")]
        ]
        await q.edit_message_text("🔧 **پنل مدیریت**",
            reply_markup=InlineKeyboardMarkup(kb), parse_mode="Markdown")

    # ──────── ورودی متنی ────────

    async def on_text(self, u, c):
        if not await is_admin(u.effective_user.id):
            return
        w = c.user_data.get("waiting_for")
        if not w:
            return
        t = u.message.text.strip()

        if w == "youtube_channel":
            await set_setting("youtube_channel_id", t)
            await u.message.reply_text(f"✅ یوتیوب: `{t}`", parse_mode="Markdown")

        elif w == "aparat_username":
            await set_setting("aparat_username", t)
            await u.message.reply_text(f"✅ آپارات: `{t}`", parse_mode="Markdown")

        elif w == "telegram_channel":
            await set_setting("telegram_channel_id", t)
            await u.message.reply_text(
                f"✅ تلگرام: `{t}`\n⚠️ بات ادمین کانال باشه!",
                parse_mode="Markdown")

        elif w == "bale_channel":
            await set_setting("bale_channel_id", t)
            await u.message.reply_text(
                f"✅ بله: `{t}`\n⚠️ بات بله ادمین کانال باشه!",
                parse_mode="Markdown")

        elif w == "bale_token":
            await set_setting("bale_bot_token", t)
            try:
                await u.message.delete()
            except:
                pass
            await u.message.reply_text("✅ توکن بله ذخیره شد!")

        elif w == "robika_channel":
            await set_setting("robika_channel_guid", t)
            await u.message.reply_text(f"✅ روبیکا: `{t}`", parse_mode="Markdown")

        elif w == "robika_auth":
            await set_setting("robika_auth", t)
            try:
                await u.message.delete()
            except:
                pass
            await u.message.reply_text("✅ توکن روبیکا ذخیره شد!")

        elif w == "add_admin":
            try:
                uid = int(t)
                await add_admin(uid, f"Admin_{uid}")
                await u.message.reply_text(f"✅ ادمین {uid} اضافه شد!")
            except ValueError:
                await u.message.reply_text("❌ آیدی عددی بفرست!")

        elif w == "custom_message":
            results = []
            # تلگرام
            ch = await get_setting("telegram_channel_id")
            if ch:
                try:
                    await self.app.bot.send_message(
                        chat_id=ch, text=t, parse_mode="HTML")
                    results.append("📢 تلگرام ✅")
                except:
                    results.append("📢 تلگرام ❌")
            # بله
            from bale_bot import BaleNotifier
            if await BaleNotifier().send_custom_message(t):
                results.append("💬 بله ✅")
            else:
                results.append("💬 بله ❌")

            await u.message.reply_text(
                "📤 نتیجه ارسال:\n" + "\n".join(results))

        c.user_data.clear()

    # ──────── ارسال به کانال تلگرام ────────

    async def send_to_telegram(self, v, platform):
        ch = await get_setting("telegram_channel_id")
        if not ch:
            return False
        try:
            msg = self._fmt(v, platform)
            if v.get("thumbnail"):
                try:
                    await self.app.bot.send_photo(
                        chat_id=ch, photo=v["thumbnail"],
                        caption=msg, parse_mode="HTML")
                    return True
                except:
                    pass
            await self.app.bot.send_message(
                chat_id=ch, text=msg, parse_mode="HTML")
            return True
        except Exception as e:
            logger.error(f"خطا تلگرام: {e}")
            return False

    def _fmt(self, v, platform):
        emoji = "🔴" if platform == "youtube" else "🎬"
        name = "YouTube" if platform == "youtube" else "آپارات"
        if v.get("type") == "live":
            return (
                f"{emoji} <b>🔴 استریم زنده!</b>\n\n"
                f"🎬 <b>{v['title']}</b>\n\n📝 {v.get('description','')}\n\n"
                f'🔗 <a href="{v["url"]}">لینک تماشا</a>\n\n'
                f"⏰ <b>بیاید ببینید!</b> 🔥")
        return (
            f"{emoji} <b>ویدیوی جدید در {name}!</b>\n\n"
            f"🎬 <b>{v['title']}</b>\n\n📝 {v.get('description','')}\n\n"
            f'🔗 <a href="{v["url"]}">لینک تماشا</a>\n\n'
            f"✨ <b>حتماً ببینید!</b>")
'''

# ============================================
# main.py  ←  آپدیت شده با بله
# ============================================
FILES["main.py"] = r'''import asyncio, logging, os
from dotenv import load_dotenv
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger

from database import init_db, get_setting, set_setting, mark_video_sent
from youtube_checker import YouTubeChecker
from aparat_checker import AparatChecker
from telegram_bot import TelegramBot
from bale_bot import BaleNotifier
from robika_bot import RobikaNotifier

load_dotenv()
logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)


class StreamNotifierBot:
    def __init__(self):
        self.yt = YouTubeChecker()
        self.ap = AparatChecker()
        self.tg = TelegramBot()
        self.bale = BaleNotifier()
        self.rb = RobikaNotifier()
        self.sched = AsyncIOScheduler()

    async def check_and_notify(self):
        if await get_setting("is_active", "true") != "true":
            return
        logger.info("🔍 چک...")

        # یوتیوب ویدیو
        try:
            for v in await self.yt.check_new_videos():
                await self._notify(v, "youtube")
                await mark_video_sent(v["id"], "youtube", v["title"])
        except Exception as e:
            logger.error(f"خطا: {e}")

        # یوتیوب استریم
        try:
            for v in await self.yt.check_live_streams():
                await self._notify(v, "youtube")
                await mark_video_sent(v["id"], "youtube", v["title"])
        except Exception as e:
            logger.error(f"خطا: {e}")

        # آپارات
        try:
            for v in await self.ap.check_new_videos():
                await self._notify(v, "aparat")
                await mark_video_sent(v["id"], "aparat", v["title"])
        except Exception as e:
            logger.error(f"خطا: {e}")

        logger.info("✅ چک تمام شد")

    async def _notify(self, v, platform):
        # ۱. تلگرام
        try:
            await self.tg.send_to_telegram(v, platform)
        except Exception as e:
            logger.error(f"خطا تلگرام: {e}")

        # ۲. بله
        try:
            await self.bale.send_notification(v, platform)
        except Exception as e:
            logger.error(f"خطا بله: {e}")

        # ۳. روبیکا
        try:
            await self.rb.send_notification(v, platform)
        except Exception as e:
            logger.error(f"خطا روبیکا: {e}")

        await asyncio.sleep(1)

    async def run(self):
        logger.info("🚀 شروع بات...")
        await init_db()
        if not await get_setting("is_active"):
            await set_setting("is_active", "true")
            await set_setting("check_interval", "120")

        app = self.tg.create_app()
        await self.rb.initialize()

        iv = int(await get_setting("check_interval", "120"))
        self.sched.add_job(self.check_and_notify,
                           IntervalTrigger(seconds=iv),
                           id="check", replace_existing=True)
        self.sched.start()
        logger.info(f"⏱ هر {iv} ثانیه")

        await self.check_and_notify()

        logger.info("🤖 بات در حال اجرا...")
        await app.initialize()
        await app.start()
        await app.updater.start_polling(drop_pending_updates=True)

        try:
            await asyncio.Event().wait()
        except (KeyboardInterrupt, SystemExit):
            logger.info("🛑 خاموش...")
        finally:
            self.sched.shutdown()
            await self.rb.close()
            await app.updater.stop()
            await app.stop()
            await app.shutdown()


if __name__ == "__main__":
    try:
        asyncio.run(StreamNotifierBot().run())
    except KeyboardInterrupt:
        print("بات خاموش شد.")
'''

FILES["README.md"] = "# Stream Notifier Bot"


def create_project():
    print("=" * 55)
    print("Stream Notifier Bot Installer")
    print("Telegram + Bale + Robika")
    print("=" * 55)
    os.makedirs(PROJECT_NAME, exist_ok=True)
    for fn, content in FILES.items():
        fp = os.path.join(PROJECT_NAME, fn)
        with open(fp, "w", encoding="utf-8") as f:
            f.write(content.strip() + "\n")
        print(f"  OK: {fn}")
    import zipfile
    zip_name = f"{PROJECT_NAME}.zip"
    with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as zf:
        for root, dirs, files in os.walk(PROJECT_NAME):
            for file in files:
                fp = os.path.join(root, file)
                zf.write(fp, os.path.relpath(fp, "."))
    print(f"\nDone! -> {zip_name}")
    print("\nNext steps:")
    print("  1. cd stream-notifier-bot")
    print("  2. nano .env  (fill tokens)")
    print("  3. pip install -r requirements.txt")
    print("  4. python main.py")


if __name__ == "__main__":
    create_project()
