import sys, time, json
from pathlib import Path
sys.path.insert(0, '/app')
from pinterest.client import PinterestClient

data_dir = Path('/app/data/pinterest')
with PinterestClient(data_dir) as client:
    client.is_authenticated()
    client.page.goto('https://www.pinterest.com/rmacsparran/_created/', timeout=30000)
    time.sleep(5)

    # Find the + button by bounding box (top right area)
    # Viewport is 1920x1080
    print('All buttons in top 150px:')
    btns = client.page.query_selector_all('button, a[role="button"], [role="button"]')
    for b in btns:
        try:
            box = b.bounding_box()
            if box and box['y'] < 150:
                txt = (b.inner_text() or '').strip()[:40]
                aria = b.get_attribute('aria-label') or ''
                testid = b.get_attribute('data-test-id') or ''
                href = b.get_attribute('href') or ''
                print(f'  x={box["x"]:.0f} y={box["y"]:.0f} w={box["width"]:.0f} | testid={testid!r} aria={aria!r} txt={txt!r} href={href[:40]!r}')
        except:
            pass

    # Also try clicking the + by bounding box
    print('\nLooking for + button (no text, top-right area)...')
    for b in btns:
        try:
            box = b.bounding_box()
            txt = (b.inner_text() or '').strip()
            if box and box['y'] < 150 and box['x'] > 1800 and not txt:
                aria = b.get_attribute('aria-label') or ''
                testid = b.get_attribute('data-test-id') or ''
                print(f'  CANDIDATE: x={box["x"]:.0f} y={box["y"]:.0f} testid={testid!r} aria={aria!r}')
                b.click()
                time.sleep(3)
                client.page.screenshot(path=str(data_dir / 'debug_plus_click.png'))
                print('  Clicked! Checking for modal...')
                for e in client.page.query_selector_all('[role="dialog"], [data-test-id*="modal"], [data-test-id*="board"]'):
                    testid2 = e.get_attribute('data-test-id') or ''
                    role2 = e.get_attribute('role') or ''
                    txt2 = (e.inner_text() or '').strip()[:80]
                    print(f'    dialog/modal: testid={testid2!r} role={role2!r} txt={txt2!r}')
                break
        except Exception as ex:
            print(f'  Error: {ex}')
