"""
RSS-Bridge kullanarak video metadata çıkarımı
"""
import feedparser
import re
import requests
import logging
from urllib.parse import urlencode
from typing import List, Dict, Optional
from datetime import datetime

logger = logging.getLogger(__name__)


def get_channel_id_from_handle(handle_url: str) -> Optional[str]:
    """
    Channel handle URL'inden Channel ID'yi web scraping ile bulur.
    Örnek: https://www.youtube.com/@tavakfi -> UC...
    
    YouTube Channel ID formatı: UC ile başlayan, 24 karakter, sadece alfanumerik ve alt çizgi
    """
    try:
        logger.info(f"[CHANNEL_ID] Channel ID çıkarılıyor: {handle_url}")
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get(handle_url, headers=headers, timeout=10)
        response.raise_for_status()
        
        html_content = response.text
        
        # YouTube Channel ID pattern: UC ile başlayan, 24 karakter, sadece alfanumerik ve alt çizgi (tire YOK)
        # Pattern'ler: UC + 22 karakter = toplam 24 karakter
        patterns = [
            (r'"externalId":"(UC[a-zA-Z0-9_]{22})"', 'externalId'),
            (r'"channelId":"(UC[a-zA-Z0-9_]{22})"', 'channelId'),
            (r'"browseEndpoint"\s*:\s*\{[^}]*"browseId"\s*:\s*"(UC[a-zA-Z0-9_]{22})"', 'browseEndpoint'),
            (r'channelId["\']?\s*:\s*["\']?(UC[a-zA-Z0-9_]{22})', 'genel channelId'),
            (r'/channel/(UC[a-zA-Z0-9_]{22})', 'URL pattern'),
        ]
        
        for pattern, pattern_name in patterns:
            match = re.search(pattern, html_content)
            if match:
                channel_id = match.group(1)
                # Double check: UC ile başlamalı ve 24 karakter olmalı
                if channel_id.startswith('UC') and len(channel_id) == 24:
                    # Tire karakteri içermemeli
                    if '-' not in channel_id:
                        logger.info(f"[CHANNEL_ID] ✅ Channel ID bulundu: {channel_id} (pattern: {pattern_name})")
                        return channel_id
                    else:
                        logger.warning(f"[CHANNEL_ID] ⚠️ Geçersiz channel ID (tire içeriyor): {channel_id}")
        
        logger.warning(f"[CHANNEL_ID] ❌ Channel ID bulunamadı: {handle_url}")
        return None
        
    except requests.exceptions.RequestException as e:
        logger.error(f"[CHANNEL_ID] ❌ Hata: {type(e).__name__} - {str(e)}")
        raise Exception(f"Error fetching channel page: {e}")


def extract_video_id(url: str) -> Optional[str]:
    """YouTube URL'den video ID çıkar"""
    patterns = [
        r'youtube\.com/watch\?v=([a-zA-Z0-9_-]{11})',
        r'youtu\.be/([a-zA-Z0-9_-]{11})',
        r'youtube\.com/embed/([a-zA-Z0-9_-]{11})'
    ]
    
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    
    return None


def fetch_videos_from_rss_bridge(base_url: str, channel_id: str, 
                                 format: str = "Atom", max_items: int = 100) -> List[Dict]:
    """
    RSS-Bridge'den video listesini çek
    
    Args:
        base_url: RSS-Bridge base URL
        channel_id: YouTube Channel ID (UC...)
        format: Feed format (Atom veya Rss)
        max_items: Maksimum video sayısı
    
    Returns:
        Video metadata listesi
    """
    params = {
        'action': 'display',
        'bridge': 'YoutubeBridge',
        'context': 'By channel id',
        'c': channel_id,
        'format': format
    }
    
    feed_url = f"{base_url}/?{urlencode(params)}"
    
    try:
        feed = feedparser.parse(feed_url)
        
        videos = []
        for entry in feed.entries[:max_items]:
            video_id = extract_video_id(entry.link)
            if not video_id:
                continue
            
            # Tarih parsing
            published_date = None
            if hasattr(entry, 'published_parsed') and entry.published_parsed:
                published_date = datetime(*entry.published_parsed[:6]).isoformat() + 'Z'
            
            videos.append({
                'video_id': video_id,
                'video_title': entry.title,
                'video_url': entry.link,
                'published_at_utc': published_date,
                'description': getattr(entry, 'summary', '')
            })
        
        return videos
        
    except Exception as e:
        raise Exception(f"Error fetching RSS-Bridge feed: {e}")

