#!/usr/bin/env python3
"""v10: Double-click grid row to open process editor → find step form."""
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 (v5/v6 working approach)
        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}")

        # Find grid rows
        rows = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('.x-grid-row, .x-grid-data-row, .x-grid-table-row, tr.x-grid-row').forEach(row => {
                items.push({
                    text: row.textContent.trim().substring(0, 100),
                    id: row.id || ''
                });
            });
            return items;
        }''')
        print(f"Grid rows: {len(rows)}")
        for r in rows[:10]:
            print(f"  #{r['id']} {r['text'][:60]}")

        # Double-click on the first grid row that contains "AP DPR" or first row
        target_row = None
        for r in rows:
            if "AP DPR" in r["text"] or "Diagnostics" in r["text"]:
                target_row = r
                break
        if not target_row and rows:
            target_row = rows[0]

        if target_row:
            row_id = target_row["id"]
            print(f"\nDouble-clicking row: #{row_id} '{target_row['text'][:40]}'")
            
            # Method 1: dispatch dblclick event
            result = await page.evaluate(f'''() => {{
                const row = document.getElementById('{row_id}');
                if (row) {{
                    row.dispatchEvent(new MouseEvent('dblclick', {{bubbles: true, cancelable: true}}));
                    return 'dblclick dispatched';
                }}
                return 'row not found';
            }}''')
            print(f"  {result}")
            await asyncio.sleep(5)
            try: await page.wait_for_load_state("networkidle", timeout=15000)
            except: pass
            
            # Check if URL changed or new content appeared
            url = page.url
            print(f"  URL after dblclick: {url}")
            
            # If still on search page, try clicking a grid cell directly
            if "showSearch" in url:
                print("  Still on search — trying cell dblclick")
                cell_result = await page.evaluate('''() => {
                    const cells = document.querySelectorAll('.x-grid-cell, .x-grid-cell-inner');
                    for (const cell of cells) {
                        if (cell.textContent && cell.textContent.includes('AP DPR')) {
                            cell.dispatchEvent(new MouseEvent('dblclick', {bubbles: true, cancelable: true}));
                            cell.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
                            return 'dblclick+click on AP DPR cell';
                        }
                    }
                    return 'not found';
                }''')
                print(f"  {cell_result}")
                await asyncio.sleep(5)
                try: await page.wait_for_load_state("networkidle", timeout=15000)
                except: pass
            
            # Method 3: Try Playwright's native dblclick
            if "showSearch" in page.url:
                print("  Trying Playwright native dblclick on grid cell")
                cells = await page.query_selector_all('.x-grid-cell')
                for cell in cells:
                    text = await cell.inner_text()
                    if "AP DPR" in text:
                        await cell.dblclick(timeout=5000)
                        await asyncio.sleep(5)
                        try: await page.wait_for_load_state("networkidle", timeout=15000)
                        except: pass
                        break

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

        # Get visible elements in the editor
        print(f"\n=== Page state ===")
        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});
                    }
                }
            });
            return items;
        }''')
        print(f"Visible: {len(visible)}")
        # Filter for relevant items
        relevant = [m for m in visible if any(k in m["text"].lower() for k in
            ["sql", "execute", "query", "step", "process", "connection", "database",
             "external", "program", "file", "ftp", "import", "export", "transform",
             "send", "mail", "copy", "move", "delete", "run", "save", "add"])]
        print(f"Relevant ({len(relevant)}):")
        for m in relevant[:25]:
            print(f"  {m['tag']}#{m['id']} '{m['text'][:50]}'")

        # Get form fields
        form = await page.evaluate('''() => {
            const fields = [];
            document.querySelectorAll('input, textarea, select').forEach(el => {
                fields.push({
                    tag: el.tagName, id: el.id||'', name: el.name||'',
                    type: el.type||'', value: (el.value||'').substring(0,50),
                    visible: el.offsetParent !== null
                });
            });
            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]}")

        # Get buttons
        buttons = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('a, 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]}'")

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

        await browser.close()

asyncio.run(main())
