#!/usr/bin/env python3
"""v8: New Process → fill name → add step → select SQL type → fill SQL → Run."""
import asyncio, json
from playwright.async_api import async_playwright

IP = "66.175.238.112"
APP = "2610RTROGERSUAP1"
BASE = f"http://{IP}/{APP}"
SQL_QUERY = "SELECT @@version AS version, DB_NAME() AS db, GETDATE() AS now"

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.lower():
                ajax.append({"m":req.method,"u":req.url.split(APP)[-1][:120],"d":req.post_data[:500] if req.post_data else None})
        page.on("request", on_req)

        # Login (working approach from v5/v6)
        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: break
            print(f"Login attempt {attempt+1} failed")
        else:
            print("Login failed"); await browser.close(); return
        print(f"✅ Login OK")

        # 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"New Process: {page.url}")

        # Step 1: Fill process name
        print("\n=== Fill process name ===")
        name_field = await page.query_selector('#textfield-1076-inputEl')
        if name_field:
            await name_field.fill("Health Check")
            print("  Filled 'Health Check'")

        desc_field = await page.query_selector('#textarea-1077-inputEl')
        if desc_field:
            await desc_field.fill("System health check")
            print("  Filled description")

        # Step 2: Save the process first (to get a process ID)
        print("\n=== Save process ===")
        save_btn = await page.query_selector('#button-1209')
        if save_btn:
            await save_btn.click(timeout=5000)
            await asyncio.sleep(3)
            print("  Saved")

        # Step 3: Find step grid and Add button
        print("\n=== Find step grid + Add button ===")
        # button-1119 had no text — might be "Add Step"
        all_buttons = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('button, .x-btn, .x-btn-inner, [role="button"]').forEach(el => {
                if (el.offsetParent !== null) {
                    const t = el.textContent.trim();
                    items.push({text: t, id: el.id||'', cls: (el.className||'').substring(0,60), tag: el.tagName});
                }
            });
            return items;
        }''')
        print(f"  Buttons ({len(all_buttons)}):")
        for b in all_buttons[:25]:
            print(f"    #{b['id']} '{b['text'][:30]}' tag={b['tag']}")

        # Look for Add/New button for steps
        add_btn = None
        for b in all_buttons:
            text_lower = b["text"].lower()
            if any(k in text_lower for k in ["add", "new", "create", "+", "add step", "new step"]):
                add_btn = b
                break
        if not add_btn:
            # button-1119 had no text — try it
            for b in all_buttons:
                if b["id"] == "button-1119" or (b["id"] == "" and b["cls"]):
                    add_btn = b
                    break

        if add_btn:
            print(f"\n  Add button found: #{add_btn['id']} '{add_btn['text'][:20]}'")
            await page.evaluate(f"document.getElementById('{add_btn['id']}')?.click()")
            await asyncio.sleep(3)
            print("  Clicked Add")
            await page.screenshot(path="/tmp/after_add.png")
        else:
            # Try clicking button-1119 directly
            print("\n  Trying button-1119 (unknown empty button)")
            result = await page.evaluate('''() => {
                const btn = document.getElementById('button-1119');
                if (btn) { btn.click(); return 'clicked button-1119'; }
                return 'not found';
            }''')
            print(f"  {result}")
            await asyncio.sleep(3)
            await page.screenshot(path="/tmp/after_1119.png")

        # Step 4: Check what appeared — step type combo?
        print("\n=== Check for step form/combo ===")
        all_inputs = await page.evaluate('''() => {
            const fields = [];
            document.querySelectorAll('input, textarea, select').forEach(el => {
                fields.push({
                    tag: el.tagName, name: el.name||'', id: el.id||'',
                    type: el.type||'', value: el.value||'',
                    visible: el.offsetParent !== null,
                    cls: (el.className||'').substring(0,50)
                });
            });
            return fields;
        }''')
        print(f"  Form fields ({len(all_inputs)}):")
        for f in all_inputs[:20]:
            vis = "✅" if f["visible"] else "❌"
            print(f"    {vis} {f['tag']} id={f['id']} type={f['type']} val={f['value'][:30]}")

        # Expand ALL visible combos to find step types
        print("\n=== Expanding combos ===")
        combo_ids = [f["id"] for f in all_inputs if f["visible"] and ("combo" in f["id"].lower() or "combo" in f["cls"].lower())]
        print(f"  Combo IDs: {combo_ids}")

        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, .x-boundlist-selected, .x-boundlist').forEach(el => {
                            if (el.offsetParent !== null) {
                                items.push(el.textContent.trim().substring(0, 80));
                            }
                        });
                        return items;
                    }''')
                    if options:
                        print(f"  {cid}: {options[:15]}")
                    # Also check for any newly visible text
                    new_text = 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 < 60 && 
                                    (t.toLowerCase().includes('sql') || t.toLowerCase().includes('execute') ||
                                     t.toLowerCase().includes('query') || t.toLowerCase().includes('database') ||
                                     t.toLowerCase().includes('external') || t.toLowerCase().includes('program') ||
                                     t.toLowerCase().includes('file') || t.toLowerCase().includes('ftp') ||
                                     t.toLowerCase().includes('mail') || t.toLowerCase().includes('import') ||
                                     t.toLowerCase().includes('export') || t.toLowerCase().includes('web') ||
                                     t.toLowerCase().includes('process') || t.toLowerCase().includes('transform') ||
                                     t.toLowerCase().includes('send') || t.toLowerCase().includes('copy') ||
                                     t.toLowerCase().includes('move') || t.toLowerCase().includes('delete'))) {
                                    items.push({text: t, id: el.id||''});
                                }
                            }
                        });
                        return items;
                    }''')
                    if new_text:
                        print(f"  New items after expand: {[m['text'][:30] for m in new_text[:10]]}")
                    await page.keyboard.press("Escape")
                    await asyncio.sleep(1)
            except Exception as e:
                print(f"  {cid}: {e}")

        # Step 5: Get ALL visible text (full page state)
        print("\n=== All visible text ===")
        all_visible = 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 < 60) {
                        items.push({text: t, id: el.id||'', tag: el.tagName});
                    }
                }
            });
            return items;
        }''')
        print(f"  Total: {len(all_visible)}")
        for m in all_visible[:30]:
            print(f"    {m['tag']}#{m['id']} '{m['text'][:40]}'")

        # Step 6: 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'][:200]}")

        await page.screenshot(path="/tmp/step_form.png")
        await browser.close()

asyncio.run(main())
