#!/usr/bin/env python3
"""
Capture Discord Video Preview via Browser Automation
"""

import asyncio
from playwright.async_api import async_playwright
import json

async def capture_discord_video_preview():
    async with async_playwright() as p:
        # Launch browser
        browser = await p.chromium.launch(
            headless=False,  # Keep visible to see what's happening
            args=['--no-sandbox', '--disable-dev-shm-usage']
        )
        
        context = await browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        )
        
        page = await context.new_page()
        
        # Intercept network requests to capture video URLs
        video_urls = []
        
        def handle_response(response):
            url = response.url
            if '.mp4' in url and 'grok' in url:
                print(f"🎯 Captured video URL: {url}")
                video_urls.append(url)
            elif 'assets.grok.com' in url:
                print(f"📡 Grok asset request: {url}")
                video_urls.append(url)
        
        page.on('response', handle_response)
        
        try:
            # Go to Discord channel
            print("🌐 Opening Discord...")
            await page.goto('https://discord.com/channels/1313154644641447986/1475722925356093612')
            
            # Wait for login prompt or channel content
            print("⏳ Waiting for page to load...")
            await page.wait_for_timeout(5000)
            
            # Check if we need to login
            if 'login' in page.url.lower():
                print("🔐 Discord login required - please login manually and press Enter")
                input("Press Enter after logging in...")
                
                # Navigate to channel again
                await page.goto('https://discord.com/channels/1313154644641447986/1475722925356093612')
                await page.wait_for_timeout(3000)
            
            # Look for the Grok message/preview
            print("🔍 Looking for Grok video preview...")
            
            # Scroll to find the message
            for i in range(5):
                await page.keyboard.press('PageUp')
                await page.wait_for_timeout(1000)
            
            # Look for video elements
            videos = await page.query_selector_all('video')
            print(f"📺 Found {len(videos)} video elements")
            
            for video in videos:
                src = await video.get_attribute('src')
                if src:
                    print(f"🎥 Video src: {src}")
                    video_urls.append(src)
            
            # Wait a bit more for any async loading
            await page.wait_for_timeout(5000)
            
            print(f"📋 Total URLs captured: {len(video_urls)}")
            for url in video_urls:
                print(f"  • {url}")
            
            return video_urls
            
        except Exception as e:
            print(f"❌ Error: {e}")
            return []
        
        finally:
            await browser.close()

if __name__ == "__main__":
    urls = asyncio.run(capture_discord_video_preview())
    
    if urls:
        print("🎉 Success! Found video URLs:")
        for url in urls:
            print(f"  {url}")
        
        # Try to download the first video URL
        if urls:
            import requests
            try:
                print(f"📥 Attempting to download: {urls[0]}")
                response = requests.get(urls[0], timeout=30)
                if response.status_code == 200:
                    with open('captured_video.mp4', 'wb') as f:
                        f.write(response.content)
                    print(f"✅ Downloaded! ({len(response.content)} bytes)")
                else:
                    print(f"❌ Download failed: {response.status_code}")
            except Exception as e:
                print(f"❌ Download error: {e}")
    else:
        print("❌ No video URLs found")