"""
RSS feed oluşturma modülü
"""
from feedgen.feed import FeedGenerator
from datetime import datetime
from typing import List, Dict
import pytz


class RSSGenerator:
    """RSS feed generator sınıfı"""
    
    def __init__(self, channel_info: Dict):
        """
        Args:
            channel_info: Kanal bilgileri (title, link, description, language)
        """
        self.fg = FeedGenerator()
        self.channel_info = channel_info
        self._setup_channel()
    
    def _setup_channel(self):
        """Channel metadata ayarla"""
        self.fg.id(self.channel_info.get('id', ''))
        self.fg.title(self.channel_info.get('title', ''))
        self.fg.link(href=self.channel_info.get('link', ''))
        self.fg.description(self.channel_info.get('description', ''))
        self.fg.language(self.channel_info.get('language', 'en'))
        self.fg.lastBuildDate(datetime.now(pytz.UTC))
    
    def add_video_entry(self, video: Dict):
        """
        Video entry ekle
        
        Args:
            video: Video metadata dict
        """
        fe = self.fg.add_entry()
        
        # GUID (video ID)
        fe.id(video['video_id'])
        
        # Title
        fe.title(video.get('video_title', ''))
        
        # Link
        fe.link(href=video.get('video_url', ''))
        
        # Published date (timezone-aware)
        if video.get('published_at_utc'):
            try:
                pub_date = datetime.fromisoformat(
                    video['published_at_utc'].replace('Z', '+00:00')
                )
                fe.published(pub_date)
            except:
                pass
        
        # Description (kısa özet)
        fe.description(video.get('description', '')[:200])
        
        # Content (tam transcript)
        # feedgen HTML içeriği için otomatik escaping yapıyor
        if video.get('transcript_clean'):
            fe.content(content=video['transcript_clean'], type='html')
    
    def generate_rss(self, output_path: str):
        """RSS feed'i dosyaya yaz"""
        self.fg.rss_file(output_path, pretty=True, extensions=True)
        print(f"RSS feed generated: {output_path}")
    
    def generate_rss_string(self) -> str:
        """RSS feed'i string olarak döndür"""
        return self.fg.rss_str(pretty=True, extensions=True)
    
    def generate_atom_string(self) -> str:
        """Atom feed'i string olarak döndür"""
        return self.fg.atom_str(pretty=True)

