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
