#!/usr/bin/env python3
"""v6: New Process — expand combo boxes, find step types."""
import asyncio, json
from playwright.async_api import async_playwright

IP = "66.175.238.112"
APP = "2610RTROGERSUAP1"
BASE = f"http://{IP}/{APP}"

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width":1920,"height":1080})
        page = await context.new_page()

        ajax = []
        async def on_req(req):
            if "/api/" in req.url or "Integration" in req.url:
                ajax.append({"m":req.method,"u":req.url.split(APP)[-1][:100],"d":req.post_data[:200] if req.post_data else None})
        page.on("request", on_req)

        # Login with retry (copied from v5 which works)
        login_ok = False
        for attempt in range(3):
            await page.goto(f"{BASE}/login", wait_until="domcontentloaded", timeout=15000)
            await asyncio.sleep(2)
            await page.fill('input[name="Email"]', 'irelyadmin')
            await page.fill('input[name="Password"]', 'i21By2015')
            await page.evaluate('''() => {
                const c = document.querySelector('input[name="Company"]');
                if (c) c.value = '01';
            }''')
            await asyncio.sleep(1)
            await page.evaluate('document.querySelector("form").submit()')
            await asyncio.sleep(10)
            try: await page.wait_for_load_state("networkidle", timeout=15000)
            except: pass
            if "login" not in page.url.lower() or "#home" in page.url:
                login_ok = True
                break
            print(f"Login attempt {attempt+1} failed")
        
        if not login_ok:
            print("Login failed after 3 attempts"); await browser.close(); return
        print(f"Login OK: {page.url}")

        # Navigate to New Process
        await page.goto(f"{BASE}/#/IP/ProcessSetup?action=new&menuId=812&moduleMenuId=806", wait_until="networkidle", timeout=20000)
        await asyncio.sleep(5)
        print(f"\nNew Process: {page.url}")

        # Get ALL visible elements
        all_elements = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('*').forEach(el => {
                if (el.children.length === 0 && el.textContent && el.offsetParent !== null) {
                    const t = el.textContent.trim();
                    if (t.length > 1 && t.length < 80) {
                        items.push({text: t, id: el.id || '', tag: el.tagName, cls: (el.className||'').substring(0,50)});
                    }
                }
            });
            return items;
        }''')

        print(f"\nVisible elements: {len(all_elements)}")
        for m in all_elements[:30]:
            print(f"  {m['tag']}#{m['id']} '{m['text'][:50]}'")

        # Find ALL input/combo fields
        form_info = await page.evaluate('''() => {
            const fields = [];
            document.querySelectorAll('input, select, textarea').forEach(el => {
                fields.push({
                    tag: el.tagName, name: el.name||'', id: el.id||'',
                    type: el.type||'', value: el.value||'',
                    placeholder: el.placeholder||'',
                    cls: (el.className||'').substring(0,50),
                    visible: el.offsetParent !== null,
                    label: ''
                });
                // Try to find associated label
                let parent = el.parentElement;
                for (let i = 0; i < 3 && parent; i++) {
                    const labelEl = parent.querySelector('label, .x-form-item-label, .x-field-label');
                    if (labelEl) {
                        fields[fields.length-1].label = labelEl.textContent.trim().substring(0,40);
                        break;
                    }
                    parent = parent.parentElement;
                }
            });
            return fields;
        }''')
        print(f"\nForm fields ({len(form_info)}):")
        for f in form_info[:20]:
            vis = "✅" if f["visible"] else "❌"
            print(f"  {vis} {f['tag']} id={f['id']} name={f['name']} type={f['type']} label='{f['label']}'")

        # Expand combo boxes by clicking them
        print(f"\n=== Expanding combos ===")
        combo_ids = [f["id"] for f in form_info if f["visible"] and "combo" in f["id"].lower()]
        for cid in combo_ids[:5]:
            try:
                el = await page.query_selector(f"#{cid}")
                if el:
                    await el.click(timeout=5000)
                    await asyncio.sleep(2)
                    options = await page.evaluate('''() => {
                        const items = [];
                        document.querySelectorAll('.x-boundlist-item, .x-combo-list-item').forEach(el => {
                            items.push(el.textContent.trim());
                        });
                        return items;
                    }''')
                    print(f"  {cid}: {options[:10]}")
                    # Close dropdown
                    await page.keyboard.press("Escape")
                    await asyncio.sleep(1)
            except Exception as e:
                print(f"  {cid}: {e}")

        # Check for buttons (Save, Execute, Add Step)
        buttons = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('button, .x-btn, input[type="submit"], a.btn').forEach(el => {
                if (el.offsetParent !== null) {
                    items.push({text: el.textContent.trim(), id: el.id||'', cls: (el.className||'').substring(0,50)});
                }
            });
            return items;
        }''')
        print(f"\nButtons ({len(buttons)}):")
        for b in buttons[:15]:
            print(f"  #{b['id']} '{b['text'][:40]}'")

        # Print AJAX
        print(f"\n=== AJAX ({len(ajax)}) ===")
        for c in ajax[:20]:
            print(f"  {c['m']} {c['u']}")
            if c['d']:
                print(f"    data: {c['d'][:120]}")

        await browser.close()

asyncio.run(main())
