from playwright.sync_api import sync_playwright
import os

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

    video_responses = []

    def on_response(resp):
        url = resp.url
        if any(x in url for x in ['.mp4', 'video', 'share-videos', 'blob']):
            print('Video response: ' + str(resp.status) + ' - ' + url[:80])
            video_responses.append({'url': url, 'status': resp.status})
            try:
                body = resp.body()
                print('  Body: ' + str(len(body)) + ' bytes, starts: ' + str(body[:20]))
            except Exception as e:
                print('  Body error: ' + str(e))

    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

    # Monitor clicks
    click_log = []

    def log_click(e):
        target = e.target
        tag = target.tagName
        href = target.get_attribute('href') or ''
        download = target.get_attribute('download') or ''
        aria = target.get_attribute('aria-label') or ''
        click_log.append({'tag': tag, 'href': href[:50], 'download': download, 'aria': aria})

    page.expose_function('__logClick', log_click)
    page.evaluate("""() => {
        document.addEventListener('click', function(e) {
            window.__logClick(e.target);
        }, true);
    }""")

    dl = page.locator('[aria-label="Descargar"]')
    if dl.count() > 0:
        box = dl.first.bounding_box()
        cx, cy = box['x'] + box['width']//2, box['y'] + box['height']//2
        page.mouse.click(cx, cy)
        print('Clicked at ' + str(cx) + ',' + str(cy))
        page.wait_for_timeout(10000)

    print('Click log:')
    for c in click_log:
        print('  ' + str(c))

    print('Video responses: ' + str(len(video_responses)))
    for r in video_responses:
        print('  ' + str(r))

    print('Files:')
    for f in sorted(os.listdir('/home/claw/videos/')):
        sz = os.path.getsize('/home/claw/videos/' + f)
        print('  ' + f + ': ' + str(sz//1024) + 'KB')

    cdp.close()