from playwright.sync_api import sync_playwright
import os, time

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

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

    # Scroll Descargar button into view
    page.evaluate("""() => {
      const btn = document.querySelectorAll("[aria-label='Descargar']")[0];
      if (btn) { btn.scrollIntoView({block: "center"}); console.log("scrolled, y:", btn.getBoundingClientRect().y); }
      else console.log("not found");
    }""")
    page.wait_for_timeout(1000)

    # Click Descargar by aria-label
    dl_btn = page.get_by_aria_label('Descargar')
    print('Found:', dl_btn.count(), 'buttons')
    if dl_btn.count() > 0:
        box = dl_btn.first.bounding_box()
        print('Box:', box)
        dl_btn.first.click()
        print('Clicked Descargar!')
        page.wait_for_timeout(10000)

    print('Files:')
    for f in sorted(os.listdir('/home/claw/videos/')):
        path = f'/home/claw/videos/{f}'
        if os.path.isfile(path):
            print(f'  {f}: {os.path.getsize(path)//1024}KB')

    cdp.close()