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, 400)')
    time.sleep(2)

    # Find and click boardActionsButton
    create_btn = client.page.query_selector('[data-test-id="boardActionsButton"]')
    if create_btn:
        print('Found boardActionsButton, clicking...')
        create_btn.click()
        time.sleep(3)
        client.page.screenshot(path=str(data_dir / 'debug_after_create_click.png'))

        # What appeared?
        new_testids = []
        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:
                    new_testids.append({'testid': testid, 'txt': txt})
            except:
                pass
        print(json.dumps(new_testids))
    else:
        print('boardActionsButton NOT found')
        # Check what boards page URL looks like
        client.page.goto('https://www.pinterest.com/rmacsparran/boards/', timeout=30000)
        time.sleep(5)
        client.page.screenshot(path=str(data_dir / 'debug_boards_url.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:
                    print(f'testid={testid!r} txt={txt!r}')
            except:
                pass
