#!/usr/bin/env python3
"""v9: Open existing Process 7 in edit mode → see step form → find SQL field."""
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.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
        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(12)
            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
        else:
            print("Login failed"); await browser.close(); return
        print("✅ Login OK")

        # Navigate to Process list
        await page.goto(f"{BASE}/#/IP/ProcessSetup?showSearch=true&menuId=810&moduleMenuId=806",
                        wait_until="networkidle", timeout=20000)
        await asyncio.sleep(5)
        print(f"Process list: {page.url}")

        # Select Process 7 (AP DPR Diagnostics) in the grid
        selected = await page.evaluate('''() => {
            const cells = document.querySelectorAll('.x-grid-cell, .x-grid-cell-inner, td, div');
            for (const cell of cells) {
                if (cell.textContent && cell.textContent.includes('AP DPR')) {
                    cell.click();
                    return 'selected: ' + cell.textContent.trim().substring(0, 40);
                }
            }
            return 'not found';
        }''')
        print(f"  {selected}")
        await asyncio.sleep(2)

        # Find and click "Open Selected" button
        open_result = await page.evaluate('''() => {
            const btns = document.querySelectorAll('a, button, span');
            for (const b of btns) {
                if (b.textContent && b.textContent.trim() === 'Open Selected' && b.offsetParent !== null) {
                    b.click();
                    return 'clicked Open Selected';
                }
            }
            return 'Open Selected not found';
        }''')
        print(f"  {open_result}")
        await asyncio.sleep(5)
        try: await page.wait_for_load_state("networkidle", timeout=15000)
        except: pass

        print(f"  URL: {page.url}")
        await page.screenshot(path="/tmp/process7_opened.png")

        # Get ALL visible elements — look for step grid, SQL field, step type
        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 < 80) {
                        items.push({text: t, id: el.id||'', tag: el.tagName, cls: (el.className||'').substring(0,40)});
                    }
                }
            });
            return items;
        }''')
        print(f"\nVisible elements: {len(visible)}")
        for m in visible[:40]:
            print(f"  {m['tag']}#{m['id']} '{m['text'][:50]}'")

        # Find form fields
        form = 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||'').substring(0,50),
                    visible: el.offsetParent !== null,
                    cls: (el.className||'').substring(0,40)
                });
            });
            return fields;
        }''')
        print(f"\nForm fields ({len(form)}):")
        for f in form[:20]:
            vis = "✅" if f["visible"] else "❌"
            print(f"  {vis} {f['tag']} id={f['id']} type={f['type']} val={f['value'][:40]}")

        # Find buttons
        buttons = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('button, .x-btn, a[role="button"], span.x-btn-inner').forEach(el => {
                if (el.offsetParent !== null && el.textContent.trim()) {
                    items.push({text: el.textContent.trim(), id: el.id||''});
                }
            });
            return items;
        }''')
        print(f"\nButtons ({len(buttons)}):")
        for b in buttons[:25]:
            print(f"  #{b['id']} '{b['text'][:30]}'")

        # Expand combos
        print("\n=== Expand combos ===")
        combo_ids = [f["id"] for f in form if f["visible"] and ("combo" in f["id"].lower() or "combo" in f["cls"].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').forEach(el => {
                            if (el.offsetParent !== null) items.push(el.textContent.trim());
                        });
                        return items;
                    }''')
                    print(f"  {cid}: {options[:15]}")
                    await page.keyboard.press("Escape")
                    await asyncio.sleep(1)
            except: pass

        # 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 browser.close()

asyncio.run(main())
