"""Test creating a single board to verify the flow works."""
import sys, time
from pathlib import Path
sys.path.insert(0, '/app')
from pinterest.client import PinterestClient

TEST_BOARD_NAME = 'RMPropWorks Test Delete'

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, [role="tab"]'):
            if 'Created' in (l.inner_text() or ''):
                l.click()
                break
    time.sleep(5)
    client.page.evaluate('window.scrollTo(0, 500)')
    time.sleep(2)

    # Step 1: Force-click the Create button to open menu
    create_btn = client.page.query_selector('[data-test-id="boardActionsButton"]')
    if not create_btn:
        print('ERROR: boardActionsButton not found')
        sys.exit(1)

    print('Opening Create menu...')
    create_btn.click(force=True)
    time.sleep(2)

    # Step 2: Click "Create board" menu item
    board_item = client.page.query_selector('[data-test-id="Create board"]')
    if not board_item:
        print('ERROR: Create board menu item not found')
        # Dump what IS visible
        for e in client.page.query_selector_all('[role="menuitem"]'):
            print(f'  menuitem: {e.inner_text()!r} testid={e.get_attribute("data-test-id")!r}')
        sys.exit(1)

    print('Clicking Create board...')
    # Use JS click to bypass interception
    client.page.evaluate('el => el.click()', board_item)
    time.sleep(3)

    # Step 3: Find the board name input
    # Try multiple selectors
    name_input = None
    for sel in [
        'input[name="name"]',
        'input[placeholder*="name" i]',
        'input[placeholder*="board" i]',
        'input[id*="name"]',
        'input[type="text"]',
    ]:
        name_input = client.page.query_selector(sel)
        if name_input:
            print(f'Name input found with: {sel!r}')
            break

    if not name_input:
        print('ERROR: Name input not found after clicking Create board')
        # Dump what appeared
        elements = client.page.evaluate('''() => {
            const results = [];
            document.querySelectorAll("input, [role='dialog'], [data-test-id]").forEach(el => {
                results.push({
                    tag: el.tagName,
                    testid: el.getAttribute("data-test-id") || "",
                    role: el.getAttribute("role") || "",
                    placeholder: el.getAttribute("placeholder") || "",
                    type: el.getAttribute("type") || "",
                    txt: (el.textContent || "").trim().substring(0, 50)
                });
            });
            return results;
        }''')
        for e in elements:
            if e['tag'] in ('INPUT', 'TEXTAREA') or e['role'] == 'dialog' or 'board' in e['testid'].lower():
                print(f'  {e}')
        sys.exit(1)

    # Step 4: Fill in board name
    print(f'Filling board name: {TEST_BOARD_NAME!r}')
    name_input.click()
    # Use keyboard.type so React onChange fires and enables the submit button
    client.page.keyboard.type(TEST_BOARD_NAME)
    time.sleep(1)

    # Step 5: Find and click the save/create button
    # Dump all buttons to see what's available in the modal
    print('Dumping all buttons to find save button...')
    elements = client.page.evaluate('''() => {
        const results = [];
        document.querySelectorAll("button").forEach(el => {
            const box = el.getBoundingClientRect();
            results.push({
                testid: el.getAttribute("data-test-id") || "",
                txt: (el.textContent || "").trim().substring(0, 40),
                type: el.getAttribute("type") || "",
                disabled: el.disabled,
                x: Math.round(box.x),
                y: Math.round(box.y)
            });
        });
        return results;
    }''')
    for e in elements:
        print(f'  button: {e}')

    # Find the submit button by type=submit or by text, avoiding the pin content
    save_btn = None
    # Use JS to find submit button
    save_el = client.page.evaluate('''() => {
        // Look for submit button or button with Create/Done text that's inside a dialog/form
        const buttons = Array.from(document.querySelectorAll("button[type='submit'], button"));
        for (const btn of buttons) {
            const txt = (btn.textContent || "").trim();
            const testid = btn.getAttribute("data-test-id") || "";
            // Must have short text (not a pin element) and relevant text
            if (txt.length < 20 && (txt === "Create" || txt === "Done" || txt === "Save" || testid.includes("save") || btn.type === "submit")) {
                return true;
            }
        }
        return false;
    }''')
    print(f'Submit button found via JS: {save_el}')

    # Click the submit button (board-form-submit-button, enabled after typing)
    try:
        # Wait briefly for button to enable
        time.sleep(0.5)
        done_btn = client.page.query_selector('[data-test-id="board-form-submit-button"]')
        if done_btn:
            disabled = done_btn.get_attribute('disabled')
            print(f'Submit button disabled={disabled!r}')
            client.page.evaluate('el => el.click()', done_btn)
            print('Submit clicked')
        else:
            print('ERROR: board-form-submit-button not found')
    except Exception as ex:
        print(f'Save click error: {ex}')
    time.sleep(4)

    print('Done! URL:', client.page.url)
    print('SUCCESS: Board created (or attempted)')
