#!/usr/bin/env python3
"""v7: Open Process 7 → select SQL step → Run → capture AJAX."""
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 or "/IP/" in req.url:
                ajax.append({
                    "method": req.method,
                    "url": req.url,
                    "path": req.url.split(APP)[-1][:120],
                    "data": req.post_data[:500] if req.post_data else None
                })
        page.on("request", on_req)

        async def on_resp(resp):
            if "/api/" in resp.url or "/Integration" in resp.url:
                try:
                    body = await resp.text()
                    print(f"  [RESP] {resp.request.method} {resp.url.split(APP)[-1][:80]} → {resp.status} ({len(body)}B)")
                    if len(body) < 200:
                        print(f"         body: {body[:200]}")
                except: pass
        page.on("response", on_resp)

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

        # Navigate to Process Setup (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"\nProcess list: {page.url}")

        # Find Process 7 (AP DPR Diagnostics) in the grid and double-click it
        result = await page.evaluate('''() => {
            const cells = document.querySelectorAll('.x-grid-cell, .x-grid-cell-inner, td');
            for (const cell of cells) {
                if (cell.textContent && cell.textContent.includes('AP DPR Diagnostics')) {
                    cell.click();
                    return 'found AP DPR Diagnostics';
                }
            }
            return 'not found';
        }''')
        print(f"  Search result: {result}")
        await asyncio.sleep(2)

        # Double-click to open the process
        result2 = await page.evaluate('''() => {
            const cells = document.querySelectorAll('.x-grid-cell, .x-grid-cell-inner, td');
            for (const cell of cells) {
                if (cell.textContent && cell.textContent.includes('AP DPR Diagnostics')) {
                    cell.dispatchEvent(new MouseEvent('dblclick', {bubbles: true}));
                    return 'double-clicked';
                }
            }
            return 'not found';
        }''')
        print(f"  Double-click: {result2}")
        await asyncio.sleep(5)
        try: await page.wait_for_load_state("networkidle", timeout=15000)
        except: pass

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

        # Get visible elements — look for steps and step types
        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"\nVisible elements: {len(visible)}")
        # Find step-related items
        step_items = [m for m in visible if any(k in m["text"].lower() for k in
            ["sql", "step", "execute", "query", "database", "send mail", "external",
             "ap account", "uspap", "process", "connection"])]
        print(f"Step/SQL items ({len(step_items)}):")
        for m in step_items[:15]:
            print(f"  {m['tag']}#{m['id']} '{m['text'][:50]}'")

        # Find the step grid — look for grid rows
        grid_rows = await page.evaluate('''() => {
            const rows = [];
            document.querySelectorAll('.x-grid-row, .x-grid-data-row, .x-grid-table-row, tr.x-grid-row').forEach(row => {
                rows.push({
                    text: row.textContent.trim().substring(0, 100),
                    id: row.id || ''
                });
            });
            return rows;
        }''')
        print(f"\nGrid rows ({len(grid_rows)}):")
        for r in grid_rows[:5]:
            print(f"  #{r['id']} {r['text'][:80]}")

        # If we found a grid row, click on it to select
        if grid_rows:
            first_row_id = grid_rows[0]["id"]
            if first_row_id:
                await page.evaluate(f"document.getElementById('{first_row_id}').click()")
                await asyncio.sleep(2)
                print(f"  Selected row: {first_row_id}")

        # Now click "Run Selected Step" button
        print(f"\n=== Clicking 'Run Selected Step' ===")
        run_btn = await page.query_selector('#button-1212')
        if run_btn:
            is_visible = await run_btn.is_visible()
            is_enabled = await run_btn.is_enabled()
            print(f"  Button visible={is_visible} enabled={is_enabled}")
            if is_visible and is_enabled:
                await run_btn.click(timeout=5000)
                await asyncio.sleep(5)
                print("  Clicked!")
                # Wait for response
                try: await page.wait_for_load_state("networkidle", timeout=15000)
                except: pass
                await page.screenshot(path="/tmp/after_run.png")
                print(f"  URL: {page.url}")
        else:
            print("  Button not found")
            # Try alternative
            await page.evaluate("document.getElementById('button-1212')?.click()")
            await asyncio.sleep(5)

        # Check for result/output
        result_text = await page.evaluate('''() => {
            // Look for alert/notify/message box
            const msgBoxes = document.querySelectorAll('.x-message-box, .x-window, .x-msgbox, .alert, .toast');
            const texts = [];
            msgBoxes.forEach(el => {
                if (el.offsetParent !== null) texts.push(el.textContent.trim().substring(0, 200));
            });
            return texts;
        }''')
        print(f"  Message boxes: {result_text[:3]}")

        # Print ALL AJAX calls
        print(f"\n=== AJAX ({len(ajax)}) ===")
        for c in ajax:
            print(f"  {c['method']} {c['path']}")
            if c['data']:
                print(f"    data: {c['data'][:200]}")

        await browser.close()

asyncio.run(main())
