"""
Enhanced RSS scrapers that download podcast episode thumbnails.
"""

from typing import Dict, List, Any, Optional
from pathlib import Path
from src.rss_scraper import RSSScraperPodcast, RSSScraperMailChimp


class RSSScraperPodcastWithImages(RSSScraperPodcast):
    """Podcast RSS scraper that downloads episode thumbnails."""
    
    def __init__(self, config):
        super().__init__(config)
        # Create media directory for Podcast
        self.media_dir = self.config.data_dir / "media" / "Podcast"
        self.media_dir.mkdir(parents=True, exist_ok=True)
        self.logger.info(f"Podcast media directory: {self.media_dir}")
    
    def _download_episode_thumbnail(self, episode_id: str, image_url: str) -> Optional[str]:
        """Download podcast episode thumbnail."""
        if not image_url:
            return None
        
        try:
            # Clean episode ID for filename
            safe_id = episode_id.replace('/', '_').replace('\\', '_')[:50]
            
            local_path = self.download_media(
                image_url,
                f"podcast_{safe_id}_thumbnail",
                "image"
            )
            if local_path:
                self.logger.info(f"Downloaded thumbnail for episode {safe_id}")
            return local_path
        except Exception as e:
            self.logger.error(f"Error downloading thumbnail for {episode_id}: {e}")
            return None
    
    def fetch_content(self, max_items: Optional[int] = None) -> List[Dict[str, Any]]:
        """Fetch RSS feed content with thumbnail downloads."""
        items = super().fetch_content(max_items)
        
        # Download thumbnails for each episode
        for item in items:
            image_url = self.extract_image_link(item)
            if image_url:
                episode_id = item.get('id') or item.get('guid', 'unknown')
                local_thumbnail = self._download_episode_thumbnail(episode_id, image_url)
                item['local_thumbnail'] = local_thumbnail
                item['thumbnail_url'] = image_url
            
            # Also store audio link for reference (but don't download)
            audio_link = self.extract_audio_link(item)
            if audio_link:
                item['audio_url'] = audio_link
        
        return items
    
    def format_markdown(self, items: List[Dict[str, Any]]) -> str:
        """Format podcast items as markdown with thumbnail references."""
        markdown_sections = []
        
        for item in items:
            section = []
            
            # ID
            item_id = item.get('id') or item.get('guid', 'N/A')
            section.append(f"# ID: {item_id}")
            section.append("")
            
            # Title
            title = item.get('title', 'Untitled')
            section.append(f"## Title: {title}")
            section.append("")
            
            # Type
            section.append("## Type: podcast")
            section.append("")
            
            # Link
            link = item.get('link', '')
            section.append(f"## Link: {link}")
            section.append("")
            
            # Audio URL
            if item.get('audio_url'):
                section.append(f"## Audio: {item['audio_url']}")
                section.append("")
            
            # Publish Date
            pub_date = item.get('published') or item.get('pubDate', '')
            section.append(f"## Publish Date: {pub_date}")
            section.append("")
            
            # Duration
            duration = item.get('itunes_duration', '')
            if duration:
                section.append(f"## Duration: {duration}")
                section.append("")
            
            # Thumbnail
            if item.get('local_thumbnail'):
                section.append("## Thumbnail:")
                # Convert to relative path for markdown
                rel_path = Path(item['local_thumbnail']).relative_to(self.config.data_dir)
                section.append(f"![Thumbnail]({rel_path})")
                section.append("")
            elif item.get('thumbnail_url'):
                section.append(f"## Thumbnail URL: {item['thumbnail_url']}")
                section.append("")
            
            # Description
            section.append("## Description:")
            
            # Try to get full content first, then summary, then description
            content = item.get('content')
            if content and isinstance(content, list) and len(content) > 0:
                content_html = content[0].get('value', '')
                if content_html:
                    content_md = self.convert_to_markdown(content_html)
                    section.append(content_md)
            elif item.get('summary'):
                summary_md = self.convert_to_markdown(item.get('summary'))
                section.append(summary_md)
            elif item.get('description'):
                desc_md = self.convert_to_markdown(item.get('description'))
                section.append(desc_md)
            
            section.append("")
            
            # iTunes metadata if available
            if item.get('itunes_author'):
                section.append(f"## Author: {item['itunes_author']}")
                section.append("")
            
            if item.get('itunes_episode'):
                section.append(f"## Episode Number: {item['itunes_episode']}")
                section.append("")
            
            if item.get('itunes_season'):
                section.append(f"## Season: {item['itunes_season']}")
                section.append("")
            
            # Separator
            section.append("-" * 50)
            section.append("")
            
            markdown_sections.append('\n'.join(section))
        
        return '\n'.join(markdown_sections)