import aiohttp, logging
from database import get_setting

logger = logging.getLogger(__name__)
BALE_API = "https://tapi.bale.ai"


class BaleNotifier:
    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:
            return False

        text = await self._format(video_info, platform)
        is_live = (video_info.get("type") == "live")
        btn_text = "🟣 Watch Live 🟣" if is_live else "🎬 تماشای ویدیو 🎬"

        # دکمه شیشه‌ای برای بله
        reply_markup = {
            "inline_keyboard": [
                [{"text": btn_text, "url": video_info["url"]}]
            ]
        }

        poster_file_id = await get_setting("stream_poster_file_id") if is_live else None
        photo = poster_file_id or video_info.get("thumbnail")

        try:
            async with aiohttp.ClientSession() as s:
                if photo and not photo.startswith("AgAC"): # اگه فایل آیدی تلگرام نباشه
                    url = f"{BALE_API}/bot{token}/sendPhoto"
                    payload = {
                        "chat_id": channel,
                        "photo": photo,
                        "caption": text,
                        "parse_mode": "HTML",
                        "reply_markup": reply_markup
                    }
                    async with s.post(url, json=payload) as r:
                        if r.status == 200:
                            return True

                url = f"{BALE_API}/bot{token}/sendMessage"
                payload = {
                    "chat_id": channel,
                    "text": text,
                    "parse_mode": "HTML",
                    "reply_markup": reply_markup
                }
                async with s.post(url, json=payload) as r:
                    return r.status == 200
        except Exception as e:
            logger.error(f"خطا بله: {e}")
            return False

    async def _format(self, v: dict, platform: str) -> str:
        p_name = "آپارات" if platform == "aparat" else "یوتیوب"
        streamer_name = await get_setting("streamer_name", "استریمر")
        if v.get("type") == "live":
            return (
                f"🟣 <b>استریم {p_name} شروع شد!</b> 🟣\n\n"
                f"📌 <b>استریمر:</b> {streamer_name}\n"
                f"🎮 <b>عنوان:</b> {v['title']}\n\n"
                f"👇 <b>همین الان جوین شید:</b>"
            )
        else:
            return (
                f"🎬 <b>ویدیوی جدید در {p_name}!</b> 🎬\n\n"
                f"📌 <b>کانال:</b> {streamer_name}\n"
                f"📝 <b>عنوان:</b> {v['title']}\n\n"
                f"👇 <b>همین الان تماشا کنید:</b>"
            )
