#!/usr/bin/env python3

# ==========================================
# SunGrab Mega v3.0.0
# URL Validator - Enhanced
# ==========================================

import re
import yt_dlp
from urllib.parse import urlparse
from utils import logger

# ==========================================
# URL Patterns
# ==========================================

URL_PATTERN = re.compile(
    r"^(https?://)"
    r"([a-zA-Z0-9.-]+)"
    r"(\.[a-zA-Z]{2,})"
    r"(/[^\s]*)?$"
)

PLAYLIST_PATTERN = re.compile(
    r"(playlist\?list=|&list=|\?list=)"
    r"([a-zA-Z0-9_-]+)"
)

SHORTS_PATTERN = re.compile(
    r"(/shorts/|youtube\.com/shorts/)"
)

# Platform-specific URL patterns
PLATFORM_PATTERNS = {
    "YouTube": re.compile(r"(youtube\.com|youtu\.be)"),
    "Facebook": re.compile(r"(facebook\.com|fb\.watch|fb\.com)"),
    "Instagram": re.compile(r"(instagram\.com|instagr\.am)"),
    "Twitter/X": re.compile(r"(twitter\.com|x\.com|t\.co)"),
    "TikTok": re.compile(r"(tiktok\.com|vm\.tiktok\.com)"),
    "Reddit": re.compile(r"(reddit\.com|redd\.it)"),
    "Twitch": re.compile(r"(twitch\.tv|clips\.twitch\.tv)"),
    "Vimeo": re.compile(r"vimeo\.com"),
    "SoundCloud": re.compile(r"(soundcloud\.com|on\.soundcloud\.com)"),
    "Dailymotion": re.compile(r"(dailymotion\.com|dai\.ly)"),
    "Bilibili": re.compile(r"(bilibili\.com|b23\.tv)"),
    "Pinterest": re.compile(r"(pinterest\.com|pin\.it)"),
    "LinkedIn": re.compile(r"(linkedin\.com|lnkd\.in)"),
    "Snapchat": re.compile(r"snapchat\.com"),
    "Spotify": re.compile(r"(spotify\.com|open\.spotify\.com)")
}

# ==========================================
# Basic URL Validation
# ==========================================

def is_valid_url(url):
    """Check if URL has valid format"""
    if not url or not isinstance(url, str):
        return False
    return bool(URL_PATTERN.match(url.strip()))

def is_playlist_url(url):
    """Check if URL is a playlist"""
    return bool(PLAYLIST_PATTERN.search(url))

def is_shorts_url(url):
    """Check if URL is YouTube Shorts"""
    return bool(SHORTS_PATTERN.search(url))

def detect_platform_from_url(url):
    """Auto-detect platform from URL"""
    if not url:
        return "Unknown"
    
    url_lower = url.lower()
    
    for platform, pattern in PLATFORM_PATTERNS.items():
        if pattern.search(url_lower):
            return platform
    
    return "Unknown"

def get_domain(url):
    """Extract domain from URL"""
    try:
        parsed = urlparse(url)
        return parsed.netloc.lower()
    except:
        return ""

def is_short_link(url):
    """Check if URL is a shortened link"""
    short_domains = ['youtu.be', 'fb.watch', 't.co', 'redd.it', 
                     'b23.tv', 'pin.it', 'lnkd.in', 'dai.ly',
                     'vm.tiktok.com', 'on.soundcloud.com']
    domain = get_domain(url)
    return domain in short_domains

# ==========================================
# URL Checking
# ==========================================

def check_url(url):
    """
    Validate URL format and accessibility
    Returns: (is_valid, message)
    """
    if not url:
        return False, "URL cannot be empty"
    
    url = url.strip()
    
    if not is_valid_url(url):
        return False, "Invalid URL format"
    
    if not url.startswith(('http://', 'https://')):
        return False, "URL must start with http:// or https://"
    
    return True, "Valid URL"

def check_supported(url, check_playlist=False, timeout=10):
    """
    Check if URL is supported by yt-dlp
    Returns: (is_supported, info_dict)
    """
    try:
        options = {
            "quiet": True,
            "no_warnings": True,
            "extract_flat": check_playlist,
            "socket_timeout": timeout,
            "retries": 3
        }

        with yt_dlp.YoutubeDL(options) as ydl:
            info = ydl.extract_info(url, download=False)

        if info:
            if check_playlist:
                if info.get('_type') == 'playlist':
                    return True, info
                else:
                    return True, info  # Single video in "playlist" URL
            return True, info

    except yt_dlp.utils.DownloadError as e:
        error_msg = str(e).lower()
        
        if "private video" in error_msg:
            logger.debug(f"Private video: {url}")
            return False, "This is a private video"
        elif "video unavailable" in error_msg:
            logger.debug(f"Video unavailable: {url}")
            return False, "Video is unavailable"
        elif "age restricted" in error_msg:
            logger.debug(f"Age restricted: {url}")
            return False, "Age-restricted content"
        elif "country" in error_msg:
            logger.debug(f"Geo-blocked: {url}")
            return False, "Content not available in your country"
        elif "login" in error_msg:
            logger.debug(f"Login required: {url}")
            return False, "Login required to access"
        else:
            logger.debug(f"Download error for {url}: {e}")
            return False, "URL is not supported or accessible"
    
    except Exception as e:
        logger.debug(f"URL check failed for {url}: {e}")
        return False, "Could not verify URL"

def get_playlist_info(url):
    """
    Extract playlist information
    Returns: (is_playlist, info_dict)
    """
    try:
        options = {
            "quiet": True,
            "no_warnings": True,
            "extract_flat": True,
            "socket_timeout": 15
        }
        
        with yt_dlp.YoutubeDL(options) as ydl:
            info = ydl.extract_info(url, download=False)
            
            if info and info.get('_type') == 'playlist':
                # Add additional useful info
                playlist_info = {
                    'title': info.get('title', 'Unknown Playlist'),
                    'playlist_count': info.get('playlist_count', 0),
                    'uploader': info.get('uploader', info.get('channel', 'Unknown')),
                    'entries': info.get('entries', []),
                    'id': info.get('id', ''),
                    'url': url
                }
                return True, playlist_info
            elif info:
                # It's a single video URL (might have playlist parameter)
                return False, "This URL points to a single video, not a playlist"
    
    except Exception as e:
        logger.debug(f"Playlist info extraction failed: {e}")
    
    return False, "Could not get playlist information"

# ==========================================
# Main Validation Functions
# ==========================================

def validate_download_url(url, check_playlist=False):
    """
    Complete URL validation for download
    Returns: (is_valid, info_or_message)
    """
    # Step 1: Basic validation
    valid, message = check_url(url)
    if not valid:
        return False, message
    
    # Step 2: Check if supported
    supported, info = check_supported(url, check_playlist)
    if not supported:
        return False, info  # info contains error message
    
    # Step 3: Success
    if isinstance(info, dict):
        # Add detected platform if not present
        if 'extractor' in info:
            platform = info['extractor'].replace(':tab', '')
        else:
            platform = detect_platform_from_url(url)
        
        info['detected_platform'] = platform
        info['is_playlist'] = info.get('_type') == 'playlist'
        info['is_shorts'] = is_shorts_url(url)
    
    return True, info

def validate_url_batch(urls):
    """
    Validate multiple URLs for batch download
    Returns: (valid_urls, invalid_urls)
    """
    valid_urls = []
    invalid_urls = []
    
    total = len(urls)
    
    for i, url in enumerate(urls, 1):
        valid, info = validate_download_url(url)
        
        if valid:
            valid_urls.append((url, info))
        else:
            invalid_urls.append((url, info))
    
    return valid_urls, invalid_urls

# ==========================================
# Quick Check Functions
# ==========================================

def quick_validate(url):
    """
    Quick validation without full yt-dlp check
    Returns: (is_valid_url_format, detected_platform)
    """
    if not is_valid_url(url):
        return False, "Invalid"
    
    platform = detect_platform_from_url(url)
    return True, platform

def is_media_url(url):
    """
    Check if URL is likely a media URL (has video/audio)
    """
    media_indicators = [
        'video', 'watch', 'shorts', 'reel', 'story',
        'clip', 'stream', 'track', 'playlist', 'album',
        'post', 'v=', 'media', 'share'
    ]
    
    url_lower = url.lower()
    return any(ind in url_lower for ind in media_indicators)

def extract_video_id(url):
    """
    Extract video ID from various platforms
    Returns: video_id or None
    """
    # YouTube
    yt_patterns = [
        r'(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/shorts/)([a-zA-Z0-9_-]+)',
        r'(?:youtube\.com/embed/)([a-zA-Z0-9_-]+)'
    ]
    
    for pattern in yt_patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    
    # Instagram
    ig_pattern = r'instagram\.com/(?:p|reel|tv)/([a-zA-Z0-9_-]+)'
    match = re.search(ig_pattern, url)
    if match:
        return match.group(1)
    
    # TikTok
    tk_pattern = r'tiktok\.com/@[\w.-]+/video/(\d+)'
    match = re.search(tk_pattern, url)
    if match:
        return match.group(1)
    
    return None

def get_url_type(url):
    """
    Determine URL type
    Returns: 'video', 'playlist', 'shorts', 'audio', or 'unknown'
    """
    if is_playlist_url(url):
        return 'playlist'
    
    if is_shorts_url(url):
        return 'shorts'
    
    domain = get_domain(url)
    
    # Audio platforms
    if any(d in domain for d in ['soundcloud.com', 'spotify.com']):
        return 'audio'
    
    return 'video'

# ==========================================
# URL Sanitization
# ==========================================

def clean_url(url):
    """
    Clean URL by removing unnecessary parameters
    """
    # Remove common tracking parameters
    tracking_params = [
        'utm_source', 'utm_medium', 'utm_campaign', 
        'utm_term', 'utm_content', 'fbclid', 'gclid',
        'ref', 'source', 'feature', 'si'
    ]
    
    try:
        parsed = urlparse(url)
        query_params = parsed.query.split('&')
        
        cleaned_params = []
        for param in query_params:
            if '=' in param:
                key = param.split('=')[0]
                if key not in tracking_params:
                    cleaned_params.append(param)
        
        cleaned_query = '&'.join(cleaned_params)
        clean = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
        
        if cleaned_query:
            clean += f"?{cleaned_query}"
        
        return clean
    except:
        return url

def normalize_url(url):
    """
    Normalize URL to standard format
    """
    url = url.strip()
    
    # Remove trailing slashes
    url = url.rstrip('/')
    
    # Ensure https
    if url.startswith('http://'):
        url = 'https://' + url[7:]
    elif not url.startswith('https://'):
        url = 'https://' + url
    
    return url

# ==========================================
# Batch Validation with Progress
# ==========================================

def validate_urls_with_progress(urls, callback=None):
    """
    Validate URLs with progress callback
    callback(current, total, url) for progress display
    """
    valid_urls = []
    invalid_urls = []
    total = len(urls)
    
    for i, url in enumerate(urls, 1):
        if callback:
            callback(i, total, url)
        
        valid, info = validate_download_url(url)
        
        if valid:
            valid_urls.append((url, info))
        else:
            invalid_urls.append((url, info))
    
    return valid_urls, invalid_urls

# ==========================================
# URL Info Display
# ==========================================

def get_url_summary(info_dict):
    """
    Get human-readable summary from URL info
    """
    if not info_dict or not isinstance(info_dict, dict):
        return "No information available"
    
    summary = []
    
    title = info_dict.get('title', 'Unknown')
    duration = info_dict.get('duration', 0)
    uploader = info_dict.get('uploader', 'Unknown')
    
    summary.append(f"📹 Title: {title}")
    
    if duration:
        minutes = duration // 60
        seconds = duration % 60
        summary.append(f"⏱️  Duration: {minutes}:{seconds:02d}")
    
    if uploader:
        summary.append(f"👤 Uploader: {uploader}")
    
    if info_dict.get('view_count'):
        summary.append(f"👁️  Views: {info_dict['view_count']:,}")
    
    return '\n'.join(summary)
