"""
Enhanced YouTube API scraper that downloads video thumbnails.
"""

from typing import List, Dict, Any, Optional
from pathlib import Path
from src.youtube_api_scraper_v2 import YouTubeAPIScraper


class YouTubeAPIScraperWithThumbnails(YouTubeAPIScraper):
    """YouTube API scraper that downloads video thumbnails."""
    
    def __init__(self, config):
        super().__init__(config)
        # Create media directory for YouTube
        self.media_dir = self.config.data_dir / "media" / "YouTube"
        self.media_dir.mkdir(parents=True, exist_ok=True)
        self.logger.info(f"YouTube media directory: {self.media_dir}")
    
    def _download_thumbnail(self, video_id: str, thumbnail_url: str) -> Optional[str]:
        """Download video thumbnail."""
        if not thumbnail_url:
            return None
        
        try:
            local_path = self.download_media(
                thumbnail_url,
                f"youtube_{video_id}_thumbnail",
                "image"
            )
            if local_path:
                self.logger.info(f"Downloaded thumbnail for video {video_id}")
            return local_path
        except Exception as e:
            self.logger.error(f"Error downloading thumbnail for {video_id}: {e}")
            return None
    
    def fetch_content(self, max_posts: int = None, fetch_captions: bool = True) -> List[Dict[str, Any]]:
        """Fetch YouTube videos with thumbnail downloads."""
        # Call parent method to get videos
        videos = super().fetch_content(max_posts, fetch_captions)
        
        # Download thumbnails for each video
        for video in videos:
            if video.get('thumbnail'):
                local_thumbnail = self._download_thumbnail(video['id'], video['thumbnail'])
                video['local_thumbnail'] = local_thumbnail
        
        return videos
    
    def fetch_video_details(self, video_ids: List[str]) -> List[Dict[str, Any]]:
        """Fetch detailed video information with thumbnail downloads."""
        if not video_ids:
            return []
        
        # YouTube API allows max 50 videos per request
        batch_size = 50
        all_videos = []
        
        for i in range(0, len(video_ids), batch_size):
            batch = video_ids[i:i + batch_size]
            
            # Check quota (1 unit per request)
            if not self._track_quota('videos_list'):
                self.logger.warning("Quota limit reached while fetching video details")
                break
            
            try:
                response = self.youtube.videos().list(
                    part='snippet,statistics,contentDetails',
                    id=','.join(batch)
                ).execute()
                
                for video in response.get('items', []):
                    # Get thumbnail URL (highest quality available)
                    thumbnail_url = (
                        video['snippet']['thumbnails'].get('maxres', {}).get('url') or 
                        video['snippet']['thumbnails'].get('high', {}).get('url') or
                        video['snippet']['thumbnails'].get('medium', {}).get('url') or
                        video['snippet']['thumbnails'].get('default', {}).get('url', '')
                    )
                    
                    # Download thumbnail
                    local_thumbnail = self._download_thumbnail(video['id'], thumbnail_url)
                    
                    video_data = {
                        'id': video['id'],
                        'title': video['snippet']['title'],
                        'description': video['snippet']['description'],
                        'published_at': video['snippet']['publishedAt'],
                        'channel_id': video['snippet']['channelId'],
                        'channel_title': video['snippet']['channelTitle'],
                        'tags': video['snippet'].get('tags', []),
                        'duration': video['contentDetails']['duration'],
                        'definition': video['contentDetails']['definition'],
                        'caption': video['contentDetails'].get('caption', 'false'),
                        'thumbnail': thumbnail_url,
                        'local_thumbnail': local_thumbnail,  # Add local thumbnail path
                        
                        # Statistics
                        'view_count': int(video['statistics'].get('viewCount', 0)),
                        'like_count': int(video['statistics'].get('likeCount', 0)),
                        'comment_count': int(video['statistics'].get('commentCount', 0)),
                        
                        # Calculate engagement metrics
                        'engagement_rate': 0,
                        'like_ratio': 0
                    }
                    
                    # Calculate engagement metrics
                    if video_data['view_count'] > 0:
                        video_data['engagement_rate'] = (
                            (video_data['like_count'] + video_data['comment_count']) / 
                            video_data['view_count']
                        ) * 100
                        video_data['like_ratio'] = (video_data['like_count'] / video_data['view_count']) * 100
                    
                    all_videos.append(video_data)
                
                # Small delay to be respectful
                import time
                time.sleep(0.1)
                
            except Exception as e:
                self.logger.error(f"Error fetching video details: {e}")
        
        return all_videos
    
    def format_markdown(self, videos: List[Dict[str, Any]]) -> str:
        """Format videos as markdown with thumbnail references."""
        markdown_sections = []
        
        for video in videos:
            section = []
            
            # ID
            section.append(f"# ID: {video.get('id', 'N/A')}")
            section.append("")
            
            # Title
            section.append(f"## Title: {video.get('title', 'Untitled')}")
            section.append("")
            
            # Type
            section.append("## Type: video")
            section.append("")
            
            # Link
            section.append(f"## Link: https://www.youtube.com/watch?v={video.get('id', '')}")
            section.append("")
            
            # Channel
            section.append(f"## Channel: {video.get('channel_title', 'N/A')}")
            section.append("")
            
            # Published Date
            section.append(f"## Published: {video.get('published_at', 'N/A')}")
            section.append("")
            
            # Duration
            if video.get('duration'):
                section.append(f"## Duration: {video['duration']}")
                section.append("")
            
            # Description
            if video.get('description'):
                section.append("## Description:")
                section.append(video['description'][:1000])  # Limit description length
                if len(video.get('description', '')) > 1000:
                    section.append("... [truncated]")
                section.append("")
            
            # Statistics
            section.append("## Statistics:")
            section.append(f"- Views: {video.get('view_count', 0):,}")
            section.append(f"- Likes: {video.get('like_count', 0):,}")
            section.append(f"- Comments: {video.get('comment_count', 0):,}")
            section.append(f"- Engagement Rate: {video.get('engagement_rate', 0):.2f}%")
            section.append(f"- Like Ratio: {video.get('like_ratio', 0):.2f}%")
            section.append("")
            
            # Caption/Transcript
            if video.get('caption_text'):
                section.append("## Transcript:")
                # Show first 500 chars of transcript
                transcript_preview = video['caption_text'][:500]
                section.append(transcript_preview)
                if len(video.get('caption_text', '')) > 500:
                    section.append("... [See full transcript below]")
                section.append("")
                
                # Add full transcript at the end
                section.append("### Full Transcript:")
                section.append(video['caption_text'])
                section.append("")
            elif video.get('caption') == 'true':
                section.append("## Captions: Available (not fetched)")
                section.append("")
            
            # Thumbnail
            if video.get('local_thumbnail'):
                section.append("## Thumbnail:")
                # Convert to relative path for markdown
                rel_path = Path(video['local_thumbnail']).relative_to(self.config.data_dir)
                section.append(f"![Thumbnail]({rel_path})")
                section.append("")
            elif video.get('thumbnail'):
                section.append(f"## Thumbnail URL: {video['thumbnail']}")
                section.append("")
            
            # Tags
            if video.get('tags'):
                section.append(f"## Tags: {', '.join(video['tags'][:10])}")  # Limit to 10 tags
                section.append("")
            
            # Separator
            section.append("-" * 50)
            section.append("")
            
            markdown_sections.append('\n'.join(section))
        
        return '\n'.join(markdown_sections)