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(4)

    # Click Created tab
    action_bar = client.page.query_selector('[data-test-id="action-bar"]')
    if action_bar:
        for l in action_bar.query_selector_all('a, button, div[role="tab"]'):
            if 'Created' in (l.inner_text() or ''):
                l.click()
                break
    time.sleep(5)
    client.page.evaluate('window.scrollTo(0, 600)')
    time.sleep(2)

    # JS click to bypass interception
    create_btn = client.page.query_selector('[data-test-id="boardActionsButton"]')
    if create_btn:
        print('Found boardActionsButton')
        # Use JS click
        client.page.evaluate('el => el.click()', create_btn)
        time.sleep(3)
        client.page.screenshot(path=str(data_dir / 'debug_after_js_click.png'))

        # Dump new elements
        results = []
        seen = set()
        for e in client.page.query_selector_all('[data-test-id]'):
            try:
                testid = e.get_attribute('data-test-id') or ''
                txt = (e.inner_text() or '').strip()[:80]
                key = testid + '|' + txt[:20]
                if key not in seen and testid:
                    seen.add(key)
                    results.append({'testid': testid, 'txt': txt})
            except:
                pass
        print(json.dumps(results))
    else:
        print('boardActionsButton NOT found')
        # Also try listing boards differently
        client.page.goto('https://www.pinterest.com/rmacsparran/boards/', timeout=30000)
        time.sleep(5)
        client.page.screenshot(path=str(data_dir / 'debug_boards_direct.png'))
        for e in client.page.query_selector_all('[data-test-id]'):
            try:
                testid = e.get_attribute('data-test-id') or ''
                txt = (e.inner_text() or '').strip()[:60]
                if testid and (txt or testid):
                    print(f'  {testid}: {txt[:40]!r}')
            except:
                pass
