"""
Instagram scraper with cumulative markdown support and image downloads.
"""

from typing import List, Dict, Any
from pathlib import Path
from src.instagram_scraper_with_images import InstagramScraperWithImages
from src.cumulative_markdown_manager import CumulativeMarkdownManager


class InstagramScraperCumulative(InstagramScraperWithImages):
    """Instagram scraper that uses cumulative markdown management."""
    
    def __init__(self, config):
        super().__init__(config)
        self.cumulative_manager = CumulativeMarkdownManager(config)
    
    def run_incremental(self, max_posts: int = 50) -> tuple:
        """Run incremental update with cumulative markdown."""
        self.logger.info(f"Running Instagram incremental update (max {max_posts} posts)")
        
        # Fetch new content
        items = self.fetch_content(max_posts=max_posts)
        
        if items:
            # Update cumulative file
            output_file = self.cumulative_manager.update_cumulative_file(items, 'Instagram')
            
            self.logger.info(f"✅ Instagram incremental: {len(items)} posts")
            self.logger.info(f"   Updated: {output_file}")
            
            # Count images
            img_count = sum(len(item.get('local_images', [])) for item in items)
            if img_count > 0:
                self.logger.info(f"   Images downloaded: {img_count}")
            
            return True, len(items), output_file
        else:
            self.logger.warning("No new Instagram posts found")
            return False, 0, None
    
    def run_backlog(self, start_from: int = 0, max_posts: int = 1000) -> tuple:
        """Run backlog capture starting from a specific post number."""
        self.logger.info(f"Running Instagram backlog (posts {start_from} to {start_from + max_posts})")
        
        # For backlog, we need to skip already captured posts
        # This is a simplified approach - in production you'd track exact post IDs
        all_items = []
        
        try:
            # Get profile
            profile = instaloader.Profile.from_username(self.loader.context, self.target_account)
            self._check_rate_limit()
            
            # Get posts
            posts = profile.get_posts()
            
            # Skip to start position
            for i, post in enumerate(posts):
                if i < start_from:
                    continue
                if i >= start_from + max_posts:
                    break
                
                try:
                    # Download images for this post
                    image_paths = self._download_post_images(post, post.shortcode)
                    
                    # Extract post data
                    post_data = {
                        'id': post.shortcode,
                        'type': self._get_post_type(post),
                        'caption': post.caption if post.caption else '',
                        'author': post.owner_username,
                        'publish_date': post.date_utc.isoformat(),
                        'link': f'https://www.instagram.com/p/{post.shortcode}/',
                        'likes': post.likes,
                        'comments': post.comments,
                        'views': post.video_view_count if hasattr(post, 'video_view_count') else None,
                        'media_count': post.mediacount if hasattr(post, 'mediacount') else 1,
                        'hashtags': list(post.caption_hashtags) if post.caption else [],
                        'mentions': list(post.caption_mentions) if post.caption else [],
                        'is_video': getattr(post, 'is_video', False),
                        'local_images': image_paths
                    }
                    
                    all_items.append(post_data)
                    
                    # Rate limiting
                    self._aggressive_delay()
                    self._check_rate_limit()
                    
                    # Progress
                    if len(all_items) % 10 == 0:
                        self.logger.info(f"Fetched {len(all_items)}/{max_posts} posts (starting from {start_from})")
                    
                except Exception as e:
                    self.logger.error(f"Error processing post: {e}")
                    continue
            
            if all_items:
                # Update cumulative file
                output_file = self.cumulative_manager.update_cumulative_file(all_items, 'Instagram')
                
                self.logger.info(f"✅ Instagram backlog: {len(all_items)} posts")
                self.logger.info(f"   Posts {start_from} to {start_from + len(all_items)}")
                self.logger.info(f"   Updated: {output_file}")
                
                return True, len(all_items), output_file
            else:
                self.logger.warning(f"No posts fetched in range {start_from} to {start_from + max_posts}")
                return False, 0, None
                
        except Exception as e:
            self.logger.error(f"Backlog error: {e}")
            return False, 0, None