#!/usr/bin/env python3
"""i21 Integration UI v5 — navigate to Processes, find SQL execution."""
import subprocess, re, json, asyncio
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 interceptor
        ajax_calls = []
        async def on_request(req):
            if "/api/" in req.url or "/Integration" in req.url:
                ajax_calls.append({
                    "method": req.method,
                    "url": req.url.split(APP)[-1][:100],
                    "data": req.post_data[:300] if req.post_data else None
                })
        page.on("request", on_request)

        # Login via JS form submit (bypass reCAPTCHA) — with retry
        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 "#home" in page.url or ("login" not in page.url.lower()):
                login_ok = True
                break
            print(f"  Login attempt {attempt+1} failed, retrying...")
        
        if not login_ok:
            print("Login failed after 3 attempts"); await browser.close(); return
        print(f"✅ Dashboard: {page.url}")

        # Expand Integration menu
        await page.evaluate("document.getElementById('menu-806').click()")
        await asyncio.sleep(3)
        print("✅ Integration menu expanded")

        # Click on "Processes"
        print("\n=== Clicking Processes ===")
        await page.evaluate("document.getElementById('menu-810').click()")
        await asyncio.sleep(5)
        try:
            await page.wait_for_load_state("networkidle", timeout=10000)
        except: pass

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

        # Get page content
        content = await page.content()
        print(f"  Page size: {len(content)}")

        # Find all visible elements
        visible_items = 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, cls: (el.className||'').substring(0,40)});
                    }
                }
            });
            return items;
        }''')
        print(f"  Visible items: {len(visible_items)}")
        for m in visible_items[:30]:
            print(f"    {m['tag']}#{m['id']} '{m['text'][:40]}'")

        # Check for process list (grid data)
        process_names = [m for m in visible_items if any(k in m["text"].lower() for k in
            ["dcc", "rack", "invoice", "eft", "ap ", "diagnostics", "process", "step"])]
        print(f"\n  Process items ({len(process_names)}):")
        for m in process_names[:10]:
            print(f"    {m['tag']}#{m['id']} '{m['text'][:50]}'")

        # Click on "New Process" to see what step types are available
        print("\n=== Clicking New Process ===")
        await page.evaluate("document.getElementById('menu-812').click()")
        await asyncio.sleep(5)
        try:
            await page.wait_for_load_state("networkidle", timeout=10000)
        except: pass

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

        # Get all form elements
        form_fields = await page.evaluate('''() => {
            const fields = [];
            document.querySelectorAll('input, textarea, select, .x-form-field, .x-form-text').forEach(el => {
                fields.push({
                    tag: el.tagName,
                    name: el.name || '',
                    id: el.id || '',
                    type: el.type || '',
                    placeholder: el.placeholder || '',
                    cls: (el.className||'').substring(0,40),
                    visible: el.offsetParent !== null
                });
            });
            return fields;
        }''')
        print(f"  Form fields: {len(form_fields)}")
        for f in form_fields[:15]:
            print(f"    {f['tag']} name={f['name']} id={f['id']} type={f['type']} vis={f['visible']}")

        # Get all visible text (might show step type options)
        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 || ''});
                }
            });
            return items;
        }''')
        # Find step type related
        step_types = [m for m in all_visible if any(k in m["text"].lower() for k in
            ["sql", "execute", "query", "external", "program", "database",
             "ftp", "file", "import", "export", "transform", "send mail",
             "web api", "copy", "move", "delete", "process"])]
        print(f"\n  Step type options ({len(step_types)}):")
        for m in step_types[:15]:
            print(f"    '{m['text'][:50]}' id={m['id']}")

        # Click on "Connections"
        print("\n=== Clicking Connections ===")
        await page.evaluate("document.getElementById('menu-811').click()")
        await asyncio.sleep(5)
        try:
            await page.wait_for_load_state("networkidle", timeout=10000)
        except: pass

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

        visible_conn = 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 || ''});
                }
            });
            return items;
        }''')
        print(f"  Visible items: {len(visible_conn)}")
        for m in visible_conn[:15]:
            print(f"    '{m['text'][:50]}' id={m['id']}")

        # Print AJAX
        print(f"\n=== AJAX calls ({len(ajax_calls)}) ===")
        for c in ajax_calls[:20]:
            print(f"  {c['method']} {c['url']}")
            if c['data']:
                print(f"    data: {c['data'][:150]}")

        await browser.close()

asyncio.run(main())
