#!/usr/bin/env python3
"""v15: Expand ExtJS combos properly (trigger click) → find step type → select SQL → fill → Save."""
import asyncio, json
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)

        # Select step + Edit
        await page.evaluate('''() => {
            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);
                    break;
                }
            }
        }''')
        await asyncio.sleep(2)
        edit_btn = await page.query_selector('#button-1092')
        if edit_btn:
            await edit_btn.click(timeout=5000)
            await asyncio.sleep(5)
            try: await page.wait_for_load_state("networkidle", timeout=10000)
            except: pass
            print("✅ Step editor opened")

        # Expand ALL combos using ExtJS API (proper expansion)
        print("\n=== Expanding combos via ExtJS ===")
        
        combo_data = await page.evaluate('''() => {
            const results = [];
            const combos = Ext.ComponentQuery.query('combobox');
            for (const combo of combos) {
                results.push({
                    id: combo.id || '',
                    value: combo.getValue ? String(combo.getValue()) : '',
                    displayValue: combo.getRawValue ? combo.getRawValue() : '',
                    visible: combo.isVisible ? combo.isVisible() : false,
                    storeCount: combo.store ? combo.store.getCount() : 0,
                    storeData: combo.store ? (function() {
                        try {
                            const items = [];
                            combo.store.each(function(r) {
                                items.push({
                                    display: r.get(combo.displayField) || r.get('text') || r.get('strName') || '',
                                    value: r.get(combo.valueField) || r.get('intStepTypeId') || ''
                                });
                            });
                            return items;
                        } catch(e) { return []; }
                    })() : []
                });
            }
            return results;
        }''')
        
        print(f"  ExtJS combos: {len(combo_data)}")
        for c in combo_data:
            print(f"    #{c['id']} val={c['value']} display={c['displayValue']} vis={c['visible']} store={c['storeCount']}")
            if c['storeData'] and len(c['storeData']) > 0:
                print(f"      Options:")
                for opt in c['storeData'][:20]:
                    marker = "🎯" if any(k in str(opt.get('display','')).lower() for k in ["sql","execute","query","database","external","program"]) else "  "
                    print(f"        {marker}{opt.get('display','')} = {opt.get('value','')}")

        # Find the combo that has step type options
        step_type_combo = None
        for c in combo_data:
            if c['storeData']:
                for opt in c['storeData']:
                    if any(k in str(opt.get('display','')).lower() for k in ["sql","execute query","database operation","execute external","send mail","ftp","file","import","export","transform","web api","copy","move","delete"]):
                        step_type_combo = c
                        break
            if step_type_combo: break

        if step_type_combo:
            print(f"\n  🎯 Step Type combo: #{step_type_combo['id']}")
            print(f"    Current: {step_type_combo['displayValue']}")
            
            # Find SQL option in step type combo
            sql_option = None
            for opt in step_type_combo['storeData']:
                if any(k in str(opt.get('display','')).lower() for k in ["execute sql","sql query"]):
                    sql_option = opt
                    break
            
            if sql_option:
                print(f"    🎯 SQL option: {sql_option}")
                
                # Select SQL option via ExtJS
                result = await page.evaluate(f'''() => {{
                    const combo = Ext.getCmp('{step_type_combo['id']}');
                    if (combo) {{
                        combo.setValue({sql_option.get('value','')});
                        combo.fireEvent('select', combo);
                        return 'selected: {sql_option.get('display','')}';
                    }}
                    return 'combo not found';
                }}''')
                print(f"    {result}")
                await asyncio.sleep(3)
                
                # Check for new form fields (SQL textarea)
                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,80), name: el.name||''});
                        }
                    });
                    return fields;
                }''')
                print(f"\n  New form fields ({len(new_form)}):")
                for f in new_form[:25]:
                    print(f"    {f['tag']} id={f['id']} type={f['type']} val={f['value'][:50]}")
                
                # Find ALL textareas
                textareas = [f for f in new_form if f["tag"] == "TEXTAREA"]
                print(f"\n  All textareas ({len(textareas)}):")
                for ta in textareas:
                    print(f"    id={ta['id']} val={ta['value'][:60]}")
                
                # Find SQL textarea (might be empty or contain SQL)
                sql_ta = None
                for ta in textareas:
                    if ta["value"] and ("usp" in ta["value"] or "select" in ta["value"].lower() or "sql" in ta["id"].lower()):
                        sql_ta = ta
                        break
                if not sql_ta and textareas:
                    # The SQL textarea might be the one that's not the description
                    for ta in textareas:
                        if ta["id"] != "textarea-1077-inputEl" and ta["id"] != "textarea-1257-inputEl":
                            sql_ta = ta
                            break
                
                if sql_ta:
                    print(f"\n  🎯 SQL Textarea: #{sql_ta['id']}")
                    ta_el = await page.query_selector(f"#{sql_ta['id']}")
                    if ta_el:
                        await ta_el.fill(SQL_QUERY)
                        print(f"  ✅ Filled SQL: {SQL_QUERY[:50]}")
                        await asyncio.sleep(1)
                        
                        # Fill step name
                        name_el = await page.query_selector('#textfield-1247-inputEl')
                        if name_el:
                            await name_el.fill("SQL Health Check")
                        
                        # Save
                        pre_save = len(all_ajax)
                        save_btn = await page.query_selector('#button-1209') or await page.query_selector('#button-1343')
                        if save_btn:
                            await save_btn.click(timeout=5000)
                            await asyncio.sleep(5)
                            try: await page.wait_for_load_state("networkidle", timeout=10000)
                            except: pass
                            print("  ✅ Save clicked")
                            
                            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'][:300]}")
                else:
                    print("  ❌ No SQL textarea found")
                    # Take screenshot for debugging
                    await page.screenshot(path="/tmp/v15_no_sql.png")
                    print("  Screenshot: /tmp/v15_no_sql.png")
            else:
                print("  ❌ No SQL option found in step type combo")
        else:
            print("  ❌ No step type combo found")

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

        await browser.close()

asyncio.run(main())
