from playwright.sync_api import sync_playwright
import os, json

with sync_playwright() as p:
    cdp = p.chromium.connect_over_cdp('http://localhost:9223')
    ctx = cdp.contexts[0]
    page = ctx.pages[0]
    
    # Monitor ALL network requests/responses when clicking Descargar
    requests = []
    responses = []
    
    def on_request(req):
        requests.append({'url': req.url, 'method': req.method})
    
    def on_response(resp):
        url = resp.url
        status = resp.status
        headers = resp.headers
        if status >= 200 and status < 400:
            responses.append({'url': url, 'status': status, 'headers': dict(headers)})
    
    page.on('request', on_request)
    page.on('response', on_response)
    
    page.goto('https://grok.com/imagine/post/23dd7313-4a69-483b-ba8c-d3427f6603f6')
    page.wait_for_timeout(5000)
    
    try:
        page.locator('[aria-label="Permitirlas todas"]').click(timeout=2000)
        page.wait_for_timeout(500)
    except:
        pass
    
    # Log what requests are going out before the click
    pre_click_urls = set(r['url'] for r in requests)
    
    # Click Descargar
    dl = page.locator('[aria-label="Descargar"]')
    if dl.count() > 0:
        dl.first.click(force=True)
        print('Clicked Descargar!')
        page.wait_for_timeout(8000)
    
    # Check new requests
    post_click_urls = set(r['url'] for r in requests)
    new_urls = post_click_urls - pre_click_urls
    print(f'\nTotal requests: {len(requests)}')
    print(f'New URLs after click:')
    for url in sorted(new_urls):
        if any(x in url for x in ['mp4', 'video', 'download', 'assets', 'x.ai', 'grok']):
            print(f'  {url[:100]}')
    
    # Save full log
    with open('/tmp/grok-reqs.json', 'w') as f:
        json.dump({'requests': requests[-50:], 'responses': responses[-50:]}, f, indent=2)
    
    print('\nSaved to /tmp/grok-reqs.json')
    print('Files in /home/claw/videos/:')
    for f in sorted(os.listdir('/home/claw/videos/')):
        sz = os.path.getsize(f'/home/claw/videos/{f}')
        print(f'  {f}: {sz//1024}KB')
    
    cdp.close()