#!/usr/bin/env python3
"""i21 Integration UI v4 — find SQL execution in menu."""
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()

        # Login via JS form submit (bypass reCAPTCHA)
        # Step 1: GET login page to get anti-forgery cookie + token
        await page.goto(f"{BASE}/login", wait_until="domcontentloaded", timeout=15000)
        await asyncio.sleep(2)
        
        # Step 2: Fill form
        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)
        
        # Step 3: Submit via JS (bypass reCAPTCHA)
        await page.evaluate('document.querySelector("form").submit()')
        await asyncio.sleep(8)
        try:
            await page.wait_for_load_state("networkidle", timeout=15000)
        except:
            pass
        
        if "login" in page.url.lower() and "#home" not in page.url:
            print("Login failed"); await browser.close(); return
        print(f"✅ Dashboard: {page.url}")

        # Get ALL text elements with their full path
        all_items = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('*').forEach(el => {
                if (el.children.length === 0 && el.textContent) {
                    const t = el.textContent.trim();
                    if (t.length > 1 && t.length < 60) {
                        // Get parent chain for context
                        let parents = [];
                        let p = el.parentElement;
                        for (let i = 0; i < 3 && p; i++) {
                            parents.push(p.tagName + (p.id ? '#' + p.id : '') + (p.className ? '.' + p.className.split(' ')[0] : ''));
                            p = p.parentElement;
                        }
                        items.push({
                            text: t,
                            id: el.id || '',
                            cls: (el.className || '').substring(0,50),
                            parents: parents.join(' > '),
                            visible: el.offsetParent !== null
                        });
                    }
                }
            });
            return items;
        }''')

        # Find Integration-related items
        int_items = [m for m in all_items if "integration" in m["text"].lower()]
        print(f"\n=== Items containing 'integration' ({len(int_items)}) ===")
        for m in int_items[:10]:
            print(f"  '{m['text'][:40]}' visible={m['visible']}")
            print(f"    parents: {m['parents']}")

        # Find ALL items that could be SQL/Execute
        sql_items = [m for m in all_items if any(k in m["text"].lower() for k in
            ["sql", "execute", "query", "external", "program", "database operation"])]
        print(f"\n=== SQL/Execute items ({len(sql_items)}) ===")
        for m in sql_items[:10]:
            print(f"  '{m['text'][:40]}' visible={m['visible']} id={m['id']}")
            print(f"    parents: {m['parents']}")

        # Check menu structure — find items with "Integration" in parent chain
        int_parent_items = [m for m in all_items if "integration" in m["parents"].lower()]
        print(f"\n=== Items under Integration parent ({len(int_parent_items)}) ===")
        for m in int_parent_items[:15]:
            print(f"  '{m['text'][:40]}' id={m['id']} visible={m['visible']}")
            print(f"    parents: {m['parents']}")

        # Click on Integration menu to expand it
        print("\n=== Expanding Integration folder ===")
        # Try multiple approaches to click Integration
        result = await page.evaluate('''() => {
            // Approach 1: find by exact text match
            const all = document.querySelectorAll('span, a, li, div');
            for (const el of all) {
                if (el.children.length === 0 && el.textContent && el.textContent.trim() === 'Integration') {
                    // Click the parent menu item (not just the text span)
                    let target = el;
                    // Go up to find clickable parent
                    while (target.parentElement && !target.onclick && target.tagName !== 'A') {
                        target = target.parentElement;
                    }
                    target.click();
                    return 'clicked: ' + target.tagName + '#' + target.id + '.' + (target.className || '').substring(0,30);
                }
            }
            return 'not found';
        }''')
        print(f"  {result}")
        await asyncio.sleep(3)

        # Check for new visible items
        new_items = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('*').forEach(el => {
                if (el.children.length === 0 && el.textContent) {
                    const t = el.textContent.trim();
                    if (t.length > 2 && t.length < 50 && el.offsetParent !== null) {
                        items.push({text: t, id: el.id || '', tag: el.tagName});
                    }
                }
            });
            return items;
        }''')
        new_sql = [m for m in new_items if any(k in m["text"].lower() for k in
            ["sql", "execute", "query", "external", "program", "database",
             "process", "step", "connection", "schedule", "import", "export",
             "transform", "file", "ftp", "send mail", "copy"])]
        print(f"\n  Visible items after expand ({len(new_sql)}):")
        for m in new_sql[:25]:
            print(f"    {m['tag']}#{m['id']} '{m['text'][:40]}'")

        await page.screenshot(path="/tmp/integration_expanded.png")

        # If SQL items found, click on them
        sql_to_click = [m for m in new_sql if "sql" in m["text"].lower() or "execute" in m["text"].lower()]
        if sql_to_click:
            print(f"\n=== Clicking SQL item: '{sql_to_click[0]['text']}' ===")
            await page.evaluate(f'''() => {{
                const el = document.getElementById('{sql_to_click[0]['id']}');
                if (el) el.click();
            }}''')
            await asyncio.sleep(5)
            await page.wait_for_load_state("networkidle", timeout=15000)
            await page.screenshot(path="/tmp/sql_page.png")
            print(f"  URL after click: {page.url}")

            # Check for SQL input
            textareas = await page.query_selector_all('textarea')
            print(f"  Textareas: {len(textareas)}")
            for i, ta in enumerate(textareas[:3]):
                info = await ta.evaluate("el => ({name: el.name, id: el.id, cls: el.className.substring(0,40)})")
                print(f"    [{i}] {info}")
        else:
            print("\n  No SQL items found — checking if Integration menu expanded")
            # Take screenshot to see current state
            await page.screenshot(path="/tmp/menu_state.png")

        await browser.close()

asyncio.run(main())
