from playwright.sync_api import sync_playwright
import subprocess, os

with sync_playwright() as p:
    cdp = p.chromium.connect_over_cdp('http://localhost:9223')
    ctx = cdp.contexts[0]
    page = ctx.pages[0]

    video_url = 'https://assets.grok.com/users/2b7b7b03-9b89-402d-8ff1-50284d81f6ee/generated/5225524a-0c48-4176-b3a2-7432d5917074/generated_video.mp4?cache=1'

    cookies = ctx.cookies(['https://grok.com', 'https://assets.grok.com', 'https://imagine-public.x.ai'])
    cookie_str = '; '.join(c['name'] + '=' + c['value'] for c in cookies)
    print('Cookies:', len(cookie_str), 'chars')

    with open('/tmp/assets-cookies.txt', 'w') as f:
        for c in cookies:
            f.write('.assets.grok.com\tTRUE\t/\tFALSE\t0\t' + c['name'] + '\t' + c['value'] + '\n')

    r = subprocess.run([
        'curl', '-L', '-A', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
        '-o', '/home/claw/videos/corrido_assets2.mp4',
        '--max-time', '60',
        '-b', '/tmp/assets-cookies.txt',
        video_url
    ], capture_output=True, text=True)
    print('curl exit:', r.returncode)
    size = os.path.getsize('/home/claw/videos/corrido_assets2.mp4') if os.path.exists('/home/claw/videos/corrido_assets2.mp4') else 0
    print('File size:', size)

    # Try page fetch
    page.goto('https://grok.com/imagine/post/23dd7313-4a69-483b-ba8c-d3427f6603f6')
    page.wait_for_timeout(3000)

    result = page.evaluate('''
        (async () => {
            try {
                const response = await fetch("https://assets.grok.com/users/2b7b7b03-9b89-402d-8ff1-50284d81f6ee/generated/5225524a-0c48-4176-b3a2-7432d5917074/generated_video.mp4?cache=1", {
                    credentials: "include"
                });
                const blob = await response.blob();
                return "status:" + response.status + ", size:" + blob.size;
            } catch(e) {
                return "error:" + e.message;
            }
        })()
    ''')
    print("Fetch result:", result)

    cdp.close()