#!/usr/bin/env python3
"""v14: Open step editor → find step type combo → change to Execute SQL Query → fill SQL → Save → Run."""
import asyncio, json, time
from playwright.async_api import async_playwright

IP = "66.175.238.112"
APP = "2610RTROGERSUAP1"
BASE = f"http://{IP}/{APP}"
SQL_QUERY = "SELECT @@version AS version, DB_NAME() AS db, GETDATE() AS now"

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()

        all_ajax = []
        async def on_req(req):
            if "/api/" in req.url or "/integration" in req.url.lower():
                all_ajax.append({"m":req.method,"u":req.url.split(APP)[-1][:150],"d":req.post_data[:1000] 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")

        # Open Process 7
        url = (f"{BASE}/#/IP/ProcessSetup?action=edit"
               "&filters%5B0%5D%5Bcolumn%5D=intProcessId"
               "&filters%5B0%5D%5Bvalue%5D=7%7C%5E%7C"
               "&totalRecords=8&searchTab=Process"
               "&menuId=810&moduleMenuId=806")
        await page.goto(url, wait_until="networkidle", timeout=20000)
        await asyncio.sleep(8)
        print(f"Process editor: {page.url}")

        # Select step via ExtJS
        result = await page.evaluate('''() => {
            try {
                const grids = Ext.ComponentQuery.query('gridpanel');
                for (const grid of grids) {
                    const store = grid.getStore();
                    if (store && store.getCount() > 0 && store.getCount() < 20) {
                        grid.getSelectionModel().select(0);
                        return 'selected in ' + grid.id + ', count=' + store.getCount();
                    }
                }
            } catch(e) { return 'error: ' + e.message; }
            return 'no grid';
        }''')
        print(f"  {result}")
        await asyncio.sleep(2)

        # Click Edit button
        edit_btn = await page.query_selector('#button-1092')
        if edit_btn:
            vis = await edit_btn.is_visible()
            print(f"  Edit visible: {vis}")
            if vis:
                await edit_btn.click(timeout=5000)
                await asyncio.sleep(5)
                try: await page.wait_for_load_state("networkidle", timeout=10000)
                except: pass
                print("  ✅ Edit clicked")

        # Now in step editor — find ALL combos and expand them
        print("\n=== Finding step type combo ===")
        
        # Get all combos
        combos = await page.evaluate('''() => {
            const items = [];
            document.querySelectorAll('input[type="text"]').forEach(el => {
                if (el.offsetParent !== null) {
                    const id = el.id || '';
                    const cls = (el.className||'');
                    // ExtJS combos have specific classes
                    if (cls.includes('x-form-field') && (cls.includes('x-form-combo') || cls.includes('combo') || id.includes('combo'))) {
                        items.push({id: id, cls: cls.substring(0,50), value: el.value, visible: true});
                    }
                }
            });
            // Also find via ExtJS
            try {
                Ext.ComponentQuery.query('combobox, combo').forEach(c => {
                    items.push({id: c.id || '', cls: 'extjs-combo', value: c.getValue ? String(c.getValue()) : '', visible: c.isVisible ? c.isVisible() : true});
                });
            } catch(e) {}
            return items;
        }''')
        print(f"  Combos found: {len(combos)}")
        for c in combos[:10]:
            print(f"    #{c['id']} val={c['value'][:30]} cls={c['cls'][:30]}")

        # Expand each combo and look for step types
        for combo in combos:
            cid = combo["id"]
            if not cid: continue
            try:
                el = await page.query_selector(f"#{cid}")
                if not el: continue
                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;
                }''')
                
                if options:
                    print(f"\n  {cid} ({combo['value'][:20]}):")
                    for opt in options[:20]:
                        marker = "🎯" if any(k in opt.lower() for k in ["sql", "execute", "query", "database"]) else "  "
                        print(f"    {marker}{opt[:50]}")
                    
                    # If we found SQL-related option, select it
                    sql_option = None
                    for opt in options:
                        if any(k in opt.lower() for k in ["execute sql", "sql query", "database operation"]):
                            sql_option = opt
                            break
                    
                    if sql_option:
                        print(f"\n  🎯 Selecting: '{sql_option}'")
                        # Click the option
                        await page.evaluate(f'''() => {{
                            const items = document.querySelectorAll('.x-boundlist-item');
                            for (const item of items) {{
                                if (item.textContent.trim() === '{sql_option}') {{
                                    item.click();
                                    return 'selected: {sql_option}';
                                }}
                            }}
                            return 'not found';
                        }}''')
                        await asyncio.sleep(3)
                        print("  ✅ Selected SQL step type")
                        
                        # Check for new form fields (SQL textarea should appear)
                        new_form = await page.evaluate('''() => {
                            const fields = [];
                            document.querySelectorAll('input, textarea, select').forEach(el => {
                                if (el.offsetParent !== null) {
                                    fields.push({tag: el.tagName, id: el.id||'', type: el.type||'', value: (el.value||'').substring(0,60), name: el.name||''});
                                }
                            });
                            return fields;
                        }''')
                        print(f"\n  New form fields ({len(new_form)}):")
                        for f in new_form[:20]:
                            print(f"    {f['tag']} id={f['id']} type={f['type']} val={f['value'][:40]}")
                        
                        # Find SQL textarea
                        sql_textareas = [f for f in new_form if f["tag"] == "TEXTAREA" and f["value"] and 
                                        ("sql" in f["id"].lower() or "usp" in f["value"].lower() or "select" in f["value"].lower())]
                        if not sql_textareas:
                            # Check all textareas
                            sql_textareas = [f for f in new_form if f["tag"] == "TEXTAREA"]
                        
                        if sql_textareas:
                            ta = sql_textareas[0]
                            print(f"\n  🎯 SQL Textarea: id={ta['id']} current_val={ta['value'][:40]}")
                            
                            # Fill with our SQL
                            ta_el = await page.query_selector(f"#{ta['id']}")
                            if ta_el:
                                await ta_el.fill(SQL_QUERY)
                                print(f"  ✅ Filled SQL: {SQL_QUERY[:50]}")
                                await asyncio.sleep(1)
                                
                                # Also fill step name
                                name_el = await page.query_selector('#textfield-1247-inputEl')
                                if name_el:
                                    await name_el.fill("SQL Health Check")
                                    print("  ✅ Filled step name")
                                
                                # Find Save button in step editor
                                save_btn = await page.query_selector('#button-1209') or await page.query_selector('#button-1343')
                                if save_btn:
                                    pre_save = len(all_ajax)
                                    await save_btn.click(timeout=5000)
                                    await asyncio.sleep(5)
                                    try: await page.wait_for_load_state("networkidle", timeout=10000)
                                    except: pass
                                    print("  ✅ Clicked Save")
                                    
                                    # Check post-save AJAX
                                    post_save = all_ajax[pre_save:]
                                    print(f"\n  Post-save AJAX ({len(post_save)}):")
                                    for req in post_save:
                                        print(f"    {req['m']} {req['u']}")
                                        if req['d']:
                                            print(f"      data: {req['d'][:200]}")
                        else:
                            print("  ❌ No SQL textarea found after step type change")
                        
                        break  # Found SQL option, stop expanding combos
                
                await page.keyboard.press("Escape")
                await asyncio.sleep(1)
            except Exception as e:
                print(f"  {cid}: {e}")
                try: await page.keyboard.press("Escape")
                except: pass

        # Print final AJAX
        print(f"\n=== ALL AJAX ({len(all_ajax)}) ===")
        for req in all_ajax[-15:]:
            print(f"  {req['m']} {req['u']}")
            if req['d']:
                print(f"    data: {req['d'][:200]}")

        await page.screenshot(path="/tmp/v14_final.png")
        await browser.close()

asyncio.run(main())
