#!/usr/bin/env python3

# ==========================================
# SunGrab Mega v2.0.3
# Multi Platform Downloader Engine - Extended
# ==========================================

import os
import yt_dlp
from concurrent.futures import ThreadPoolExecutor, as_completed
from config import (
    Colors, DOWNLOAD_PATH, FILENAME_TEMPLATE,
    PLAYLIST_FILENAME_TEMPLATE, PROXY, COOKIE_FILE,
    DEFAULT_SPEED_LIMIT, MAX_WORKERS
)
from utils import (
    msg_info, msg_error, msg_success, msg_warning,
    save_to_history, get_file_size, logger, check_internet
)
from dashboard import (
    show_download_header, show_complete, show_error, 
    create_progress, show_batch_status, show_batch_summary
)

# ==========================================
# Platform-Specific Configurations
# ==========================================

PLATFORM_CONFIG = {
    "YouTube": {
        "extractor": "youtube",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": True,
        "playlist": True,
        "live": True,
        "shorts": True
    },
    "Facebook": {
        "extractor": "facebook",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False,
        "cookies_required": True
    },
    "Instagram": {
        "extractor": "instagram",
        "formats": ["best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False,
        "cookies_required": True,
        "types": ["reel", "story", "post", "igtv"]
    },
    "Twitter/X": {
        "extractor": "twitter",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False,
        "cookies_required": True
    },
    "TikTok": {
        "extractor": "tiktok",
        "formats": ["best", "bestvideo+bestaudio/best"],
        "merge": "mp4",
        "subtitles": False,
        "watermark_modes": True
    },
    "Reddit": {
        "extractor": "reddit",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False,
        "nsfw_filter": True
    },
    "Twitch": {
        "extractor": "twitch",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False,
        "clips": True,
        "vods": True
    },
    "Vimeo": {
        "extractor": "vimeo",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": True
    },
    "SoundCloud": {
        "extractor": "soundcloud",
        "formats": ["bestaudio/best"],
        "merge": "mp3",
        "subtitles": False,
        "audio_only": True
    },
    "Dailymotion": {
        "extractor": "dailymotion",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": True
    },
    "Bilibili": {
        "extractor": "bilibili",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False
    },
    "Pinterest": {
        "extractor": "pinterest",
        "formats": ["best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False
    },
    "LinkedIn": {
        "extractor": "linkedin",
        "formats": ["bestvideo+bestaudio/best", "bestaudio/best"],
        "merge": "mp4",
        "subtitles": False
    },
    "Snapchat": {
        "extractor": "snapchat",
        "formats": ["best", "bestvideo+bestaudio/best"],
        "merge": "mp4",
        "subtitles": False
    },
    "Spotify": {
        "extractor": "spotify",
        "formats": ["bestaudio/best"],
        "merge": "mp3",
        "subtitles": False,
        "audio_only": True,
        "types": ["track", "playlist", "album"]
    }
}

# ==========================================
# Progress Hook
# ==========================================

class ProgressHook:
    def __init__(self, progress, task):
        self.progress = progress
        self.task = task
        self.last_percent = 0

    def __call__(self, data):
        if data["status"] == "downloading":
            total = data.get("total_bytes") or data.get("total_bytes_estimate", 0)
            downloaded = data.get("downloaded_bytes", 0)
            speed = data.get("speed", 0)
            
            if total:
                percent = int(downloaded / total * 100)
                if percent > self.last_percent:
                    self.progress.update(self.task, completed=percent)
                    self.last_percent = percent
                    
        elif data["status"] == "finished":
            self.progress.update(self.task, completed=100)

# ==========================================
# Base Options Builder
# ==========================================

def build_options(path, hook, platform, media_type, template=None, **kwargs):
    """Build yt-dlp options based on platform and media type"""
    
    config = PLATFORM_CONFIG.get(platform, {})
    
    options = {
        "outtmpl": os.path.join(path, template or FILENAME_TEMPLATE),
        "progress_hooks": [hook] if hook else [],
        "quiet": True,
        "noprogress": True,
        "ignoreerrors": False,
        "retries": 10,
        "fragment_retries": 10,
        "continue_dl": True,  # Resume support
        "nocheckcertificate": True,
        "no_warnings": True,
        "extract_flat": False,
        "socket_timeout": 30,
        "extractor_retries": 3,
    }

    # Format selection
    if config.get("audio_only") or media_type == "audio":
        options["format"] = "bestaudio/best"
        options["postprocessors"] = [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "192"
        }]
    else:
        options["format"] = config.get("formats", ["bestvideo+bestaudio/best"])[0]
        options["merge_output_format"] = config.get("merge", "mp4")

    # Subtitles
    if kwargs.get("subtitles") and config.get("subtitles"):
        options["writesubtitles"] = True
        options["writeautomaticsub"] = True
        options["subtitleslangs"] = kwargs.get("sub_langs", ["en", "bn", "hi"])
        options["embedsubs"] = True

    # Cookies for platforms that need auth
    if config.get("cookies_required"):
        if COOKIE_FILE and os.path.exists(COOKIE_FILE):
            options["cookiefile"] = COOKIE_FILE
        else:
            options["cookiesfrombrowser"] = ("chrome",)  # Fallback to browser cookies

    # Proxy
    if PROXY:
        options["proxy"] = PROXY

    # Speed limit
    if DEFAULT_SPEED_LIMIT:
        options["ratelimit"] = DEFAULT_SPEED_LIMIT

    # Playlist options
    if kwargs.get("is_playlist"):
        if kwargs.get("playlist_range"):
            options["playlist_items"] = kwargs["playlist_range"]
        options["playlistend"] = kwargs.get("playlist_end", -1)
        options["playliststart"] = kwargs.get("playlist_start", 1)

    # Thumbnail
    if kwargs.get("embed_thumbnail", True):
        options["writethumbnail"] = True
        options["embedthumbnail"] = True

    # Metadata
    if kwargs.get("add_metadata", True):
        options["addmetadata"] = True

    # Age restriction bypass
    options["age_limit"] = kwargs.get("age_limit", 99)

    return options

# ==========================================
# Core Download Functions
# ==========================================

def download_video(url, path, platform="Unknown", title=None, template=None, **kwargs):
    """Download video with progress and platform-specific optimizations"""
    if not check_internet():
        show_error("No internet connection!")
        return False

    show_download_header(platform, "Video")
    progress = create_progress()
    task = progress.add_task("⬇️  Downloading video...", total=100)
    
    hook = ProgressHook(progress, task)
    options = build_options(path, hook, platform, "video", template, **kwargs)

    try:
        os.makedirs(path, exist_ok=True)
        with progress:
            with yt_dlp.YoutubeDL(options) as ydl:
                info = ydl.extract_info(url, download=True)
        
        filename = info.get("title", "Video")
        ext = options.get("merge_output_format", "mp4")
        filepath = os.path.join(path, f"{filename}.{ext}")
        size = get_file_size(filepath)

        save_to_history(url, platform, "completed", filepath, size)
        show_complete(filename)
        
        # Show extra info
        if info.get("duration"):
            msg_info(f"Duration: {info['duration']}s | Size: {size}")
        
        return True

    except yt_dlp.utils.DownloadError as e:
        error_msg = str(e)
        if "HTTP Error 403" in error_msg:
            show_error("Access denied! Try using cookies or proxy.")
        elif "HTTP Error 404" in error_msg:
            show_error("Video not found! It may have been deleted.")
        elif "Private video" in error_msg:
            show_error("This is a private video! Cannot access.")
        elif "Age restricted" in error_msg:
            show_error("Age-restricted content! Cannot bypass.")
        else:
            show_error(f"Download Error: {error_msg[:100]}")
        
        logger.error(f"Download error for {platform}: {e}")
        save_to_history(url, platform, "failed", error_msg[:100])
        return False
        
    except Exception as e:
        show_error(f"Unexpected error: {str(e)[:100]}")
        logger.error(f"Error downloading from {platform}: {e}")
        save_to_history(url, platform, "failed", str(e)[:100])
        return False

def download_audio(url, path, platform="Unknown", **kwargs):
    """Download audio only with metadata"""
    if not check_internet():
        show_error("No internet connection!")
        return False

    show_download_header(platform, "Audio Only 🎵")
    progress = create_progress()
    task = progress.add_task("🎵 Downloading audio...", total=100)

    hook = ProgressHook(progress, task)
    options = build_options(path, hook, platform, "audio", **kwargs)
    options["addmetadata"] = True

    try:
        os.makedirs(path, exist_ok=True)
        with progress:
            with yt_dlp.YoutubeDL(options) as ydl:
                info = ydl.extract_info(url, download=True)

        filename = info.get("title", "Audio")
        filepath = os.path.join(path, f"{filename}.mp3")
        size = get_file_size(filepath)

        save_to_history(url, platform, "completed", filepath, size)
        show_complete(filename)
        
        # Show audio info
        if info.get("artist"):
            msg_info(f"Artist: {info['artist']} | Size: {size}")
        
        return True

    except Exception as e:
        show_error(str(e)[:100])
        logger.error(f"Error downloading audio: {e}")
        save_to_history(url, platform, "failed", str(e)[:100])
        return False

def download_video_with_subs(url, path, platform="Unknown", **kwargs):
    """Download video with embedded subtitles"""
    kwargs["subtitles"] = True
    kwargs["sub_langs"] = kwargs.get("sub_langs", ["en", "bn", "hi", "es", "ar"])
    
    return download_video(url, path, platform, **kwargs)

def download_playlist(url, path, platform="YouTube", range_str=None, **kwargs):
    """Download full playlist with progress"""
    if not check_internet():
        show_error("No internet connection!")
        return False

    show_download_header(platform, "Playlist 📋")
    progress = create_progress()
    task = progress.add_task("📋 Downloading playlist...", total=100)

    hook = ProgressHook(progress, task)
    options = build_options(
        path, hook, platform, "video", 
        PLAYLIST_FILENAME_TEMPLATE,
        is_playlist=True,
        playlist_range=range_str,
        **kwargs
    )

    try:
        os.makedirs(path, exist_ok=True)
        with progress:
            with yt_dlp.YoutubeDL(options) as ydl:
                info = ydl.extract_info(url, download=True)

        playlist_title = info.get("title", "Playlist")
        video_count = info.get("playlist_count", 0)
        
        save_to_history(url, platform, "completed", path, 0)
        show_complete(playlist_title)
        msg_success(f"✅ Downloaded {video_count} videos from playlist!")
        return True

    except Exception as e:
        show_error(str(e)[:100])
        logger.error(f"Playlist download error: {e}")
        save_to_history(url, platform, "failed", str(e)[:100])
        return False

# ==========================================
# Special Platform Downloaders
# ==========================================

def download_tiktok(url, path, mode="with_watermark", **kwargs):
    """Download TikTok with watermark options"""
    if not check_internet():
        show_error("No internet connection!")
        return False

    watermark_text = "With Watermark" if mode == "with_watermark" else "Without Watermark"
    show_download_header("TikTok", f"Video ({watermark_text})")
    progress = create_progress()
    task = progress.add_task("📱 Downloading TikTok...", total=100)

    hook = ProgressHook(progress, task)
    options = build_options(path, hook, "TikTok", "video", **kwargs)
    
    # TikTok specific
    if mode == "without_watermark":
        options["format"] = "best"
        options["format_sort"] = ["codec:h264"]

    try:
        os.makedirs(path, exist_ok=True)
        with progress:
            with yt_dlp.YoutubeDL(options) as ydl:
                info = ydl.extract_info(url, download=True)

        filename = info.get("title", "TikTok Video")
        filepath = os.path.join(path, f"{filename}.mp4")
        size = get_file_size(filepath)

        save_to_history(url, "TikTok", "completed", filepath, size)
        show_complete(filename)
        return True

    except Exception as e:
        show_error(str(e)[:100])
        logger.error(f"TikTok download error: {e}")
        save_to_history(url, "TikTok", "failed", str(e)[:100])
        return False

def download_instagram(url, path, media_type="reel", **kwargs):
    """Download Instagram content (Reel/Story/Post)"""
    if not check_internet():
        show_error("No internet connection!")
        return False

    show_download_header("Instagram", f"{media_type.title()}")
    progress = create_progress()
    task = progress.add_task(f"📸 Downloading Instagram {media_type}...", total=100)

    hook = ProgressHook(progress, task)
    options = build_options(path, hook, "Instagram", "video", **kwargs)

    try:
        os.makedirs(path, exist_ok=True)
        with progress:
            with yt_dlp.YoutubeDL(options) as ydl:
                info = ydl.extract_info(url, download=True)

        filename = info.get("title", f"Instagram {media_type}")
        filepath = os.path.join(path, f"{filename}.mp4")
        size = get_file_size(filepath)

        save_to_history(url, "Instagram", "completed", filepath, size)
        show_complete(filename)
        return True

    except Exception as e:
        show_error(str(e)[:100])
        logger.error(f"Instagram download error: {e}")
        save_to_history(url, "Instagram", "failed", str(e)[:100])
        return False

def download_spotify(url, path, **kwargs):
    """Download Spotify tracks/playlists"""
    if not check_internet():
        show_error("No internet connection!")
        return False

    show_download_header("Spotify", "Audio 🎵")
    progress = create_progress()
    task = progress.add_task("🎵 Downloading from Spotify...", total=100)

    hook = ProgressHook(progress, task)
    options = build_options(path, hook, "Spotify", "audio", **kwargs)

    try:
        os.makedirs(path, exist_ok=True)
        with progress:
            with yt_dlp.YoutubeDL(options) as ydl:
                info = ydl.extract_info(url, download=True)

        title = info.get("title", "Spotify Track")
        filepath = os.path.join(path, f"{title}.mp3")
        size = get_file_size(filepath)

        save_to_history(url, "Spotify", "completed", filepath, size)
        show_complete(title)
        
        if info.get("artist"):
            msg_info(f"Artist: {info['artist']} | Album: {info.get('album', 'N/A')}")
        
        return True

    except Exception as e:
        show_error(str(e)[:100])
        logger.error(f"Spotify download error: {e}")
        save_to_history(url, "Spotify", "failed", str(e)[:100])
        return False

# ==========================================
# Batch Download System
# ==========================================

def download_batch(urls, path, media_type, platform, mode="sequential", **kwargs):
    """Download multiple URLs with parallel/sequential mode"""
    if not urls:
        msg_warning("No URLs to download")
        return []

    msg_info(f"🚀 Starting batch download: {len(urls)} URLs ({mode} mode)")
    results = []

    if mode == "parallel":
        with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(urls))) as executor:
            futures = {}
            for i, url in enumerate(urls, 1):
                future = executor.submit(
                    download_single,
                    url, path, media_type, platform, **kwargs
                )
                futures[future] = (i, url)

            for future in as_completed(futures):
                i, url = futures[future]
                try:
                    result = future.result()
                    results.append((url, result))
                    show_batch_status(i, len(urls), url)
                except Exception as e:
                    logger.error(f"Error downloading {url}: {e}")
                    results.append((url, False))
    else:
        for i, url in enumerate(urls, 1):
            show_batch_status(i, len(urls), url)
            result = download_single(url, path, media_type, platform, **kwargs)
            results.append((url, result))

    # Show summary
    show_batch_summary(results)
    return results

def download_single(url, path, media_type, platform, **kwargs):
    """Download a single URL with routing"""
    platform_lower = platform.lower()
    
    # Route to platform-specific downloaders
    if platform_lower == "tiktok":
        return download_tiktok(url, path, kwargs.get("tiktok_mode", "with_watermark"))
    elif platform_lower == "instagram":
        return download_instagram(url, path, kwargs.get("ig_type", "reel"))
    elif platform_lower == "spotify":
        return download_spotify(url, path)
    
    # Standard routing by media type
    if media_type == "audio":
        return download_audio(url, path, platform, **kwargs)
    elif media_type == "video_with_subs":
        return download_video_with_subs(url, path, platform, **kwargs)
    else:
        return download_video(url, path, platform, **kwargs)

# ==========================================
# Main Entry Point
# ==========================================

def download_media(url, path, media_type, platform, **kwargs):
    """Main download dispatcher"""
    if not check_internet():
        show_error("No internet connection! 🌐")
        return False

    # Handle playlist
    if kwargs.get("is_playlist") or "playlist" in url.lower():
        range_str = kwargs.get("playlist_range")
        return download_playlist(url, path, platform, range_str, **kwargs)

    # Route to appropriate downloader
    platform_lower = platform.lower()
    
    if platform_lower == "tiktok":
        mode = kwargs.get("tiktok_mode", "with_watermark")
        return download_tiktok(url, path, mode, **kwargs)
    elif platform_lower == "instagram":
        ig_type = kwargs.get("ig_type", "reel")
        return download_instagram(url, path, ig_type, **kwargs)
    elif platform_lower == "spotify":
        return download_spotify(url, path, **kwargs)
    
    # Standard download
    if media_type == "audio":
        return download_audio(url, path, platform, **kwargs)
    elif media_type == "video_with_subs":
        return download_video_with_subs(url, path, platform, **kwargs)
    else:
        return download_video(url, path, platform, **kwargs)
