#!/usr/bin/env python3
"""
Discord Video Preview Extractor
Captura URLs de vídeo quando o Discord faz preview
"""

import requests
import json
import time
import re
from urllib.parse import urlparse

def extract_video_from_discord_api(message_id, channel_id, user_token):
    """Extrai URL do vídeo via API do Discord"""
    
    headers = {
        'Authorization': user_token,
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    
    # Get message details via Discord API
    url = f"https://discord.com/api/v9/channels/{channel_id}/messages/{message_id}"
    
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            message_data = response.json()
            
            # Check embeds for video URLs
            if 'embeds' in message_data:
                for embed in message_data['embeds']:
                    if 'video' in embed:
                        video_url = embed['video'].get('url') or embed['video'].get('proxy_url')
                        if video_url:
                            print(f"🎯 Found video URL in embed: {video_url}")
                            return video_url
                    
                    # Check for thumbnail that might be a video preview
                    if 'thumbnail' in embed:
                        thumb_url = embed['thumbnail'].get('url') or embed['thumbnail'].get('proxy_url')
                        if thumb_url and ('.mp4' in thumb_url or 'video' in thumb_url):
                            print(f"🎯 Found video thumbnail: {thumb_url}")
                            return thumb_url
            
            # Check attachments
            if 'attachments' in message_data:
                for attachment in message_data['attachments']:
                    if attachment.get('content_type', '').startswith('video/'):
                        video_url = attachment.get('url') or attachment.get('proxy_url')
                        if video_url:
                            print(f"🎯 Found video attachment: {video_url}")
                            return video_url
            
            print("❌ No video found in message")
            print(f"Message data: {json.dumps(message_data, indent=2)}")
            return None
            
        else:
            print(f"❌ Discord API error: {response.status_code} - {response.text}")
            return None
            
    except Exception as e:
        print(f"❌ Error accessing Discord API: {e}")
        return None

def download_video_via_discord_proxy(video_url, output_path):
    """Baixa vídeo usando o proxy do Discord"""
    
    if not video_url:
        return False
    
    # Try to download using Discord's CDN proxy
    headers = {
        'User-Agent': 'Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)',
        'Referer': 'https://discord.com/'
    }
    
    try:
        print(f"📥 Downloading from: {video_url}")
        response = requests.get(video_url, headers=headers, stream=True, timeout=30)
        
        if response.status_code == 200:
            with open(output_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
            
            print(f"✅ Downloaded: {output_path} ({len(open(output_path, 'rb').read())} bytes)")
            return True
        else:
            print(f"❌ Download failed: {response.status_code} - {response.text}")
            return False
            
    except Exception as e:
        print(f"❌ Download error: {e}")
        return False

if __name__ == "__main__":
    # Configuration
    MESSAGE_ID = "1475732796147503114"  # ID da mensagem com o link do Grok
    CHANNEL_ID = "1475722925356093612"  # Canal #visionaryfx
    
    # Try to read Discord token
    try:
        with open('/tmp/discord_token.txt', 'r') as f:
            USER_TOKEN = f.read().strip()
    except:
        print("❌ Discord token not found. Please save it to /tmp/discord_token.txt")
        exit(1)
    
    print("🔍 Extracting video from Discord preview...")
    video_url = extract_video_from_discord_api(MESSAGE_ID, CHANNEL_ID, USER_TOKEN)
    
    if video_url:
        print("💾 Downloading video...")
        success = download_video_via_discord_proxy(video_url, "discord_extracted_video.mp4")
        
        if success:
            print("🎉 SUCCESS! Video extracted via Discord proxy!")
        else:
            print("❌ Failed to download video")
    else:
        print("❌ Could not extract video URL from Discord")