#!/usr/bin/env python3
"""v16: Change SQL Type combo to 'SQL Statement' → fill SQL → Save → Execute."""
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")

        # Change SQL Type combo from "Stored Procedure" (2) to "SQL Statement" (3)
        print("\n=== Changing SQL Type to 'SQL Statement' ===")
        result = await page.evaluate('''() => {
            const combo = Ext.getCmp('combo-1264');
            if (combo) {
                combo.setValue(3);  // SQL Statement
                combo.fireEvent('select', combo);
                return 'set to SQL Statement (3), rawValue=' + combo.getRawValue();
            }
            return 'combo not found';
        }''')
        print(f"  {result}")
        await asyncio.sleep(3)

        # Check for new form fields (SQL textarea should now 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,100), name: el.name||''});
                }
            });
            return fields;
        }''')
        print(f"\n  Form fields ({len(new_form)}):")
        for f in new_form[:25]:
            print(f"    {f['tag']} id={f['id']} type={f['type']} val={f['value'][:60]}")

        # Find SQL textarea
        textareas = [f for f in new_form if f["tag"] == "TEXTAREA"]
        print(f"\n  Textareas ({len(textareas)}):")
        for ta in textareas:
            print(f"    id={ta['id']} val={ta['value'][:60]}")
            if ta["value"] and ("usp" in ta["value"] or "select" in ta["value"].lower() or "sql" in ta["value"].lower()):
                print(f"    🎯 SQL FIELD!")

        # Also find via ExtJS
        extjs_fields = await page.evaluate('''() => {
            const results = [];
            Ext.ComponentQuery.query('textarea, textareafield').forEach(c => {
                results.push({
                    id: c.id || '',
                    value: c.getValue ? c.getValue() : '',
                    visible: c.isVisible ? c.isVisible() : true,
                    fieldLabel: c.fieldLabel || ''
                });
            });
            return results;
        }''')
        print(f"\n  ExtJS textareas ({len(extjs_fields)}):")
        for f in extjs_fields:
            print(f"    #{f['id']} label='{f['fieldLabel']}' val={f['value'][:60]} vis={f['visible']}")

        # Find the SQL textarea (the one with uspAPCompareBalance or empty)
        sql_ta_id = None
        for f in extjs_fields:
            val = f.get("value", "")
            if "uspAPCompareBalance" in val or "usp" in val.lower():
                sql_ta_id = f["id"]
                print(f"\n  🎯 Found SQL field: #{sql_ta_id} (contains uspAPCompareBalance)")
                break
        
        if not sql_ta_id:
            # Try finding by label
            for f in extjs_fields:
                label = f.get("fieldLabel", "").lower()
                if "sql" in label or "query" in label or "command" in label:
                    sql_ta_id = f["id"]
                    print(f"\n  🎯 Found SQL field by label: #{sql_ta_id} (label='{f['fieldLabel']}')")
                    break
        
        if not sql_ta_id:
            # Find any NEW textarea that wasn't there before
            for f in new_form:
                if f["tag"] == "TEXTAREA" and f["id"] not in ("textarea-1077-inputEl", "textarea-1257-inputEl"):
                    sql_ta_id = f["id"]
                    print(f"\n  🎯 Found new textarea: #{sql_ta_id}")
                    break

        if sql_ta_id:
            # Fill with our SQL
            await page.evaluate(f'''() => {{
                const field = Ext.getCmp('{sql_ta_id}');
                if (field) {{
                    field.setValue('{SQL_QUERY}');
                    field.fireEvent('change', field);
                    return 'set value: {SQL_QUERY}';
                }}
                return 'not found';
            }}''')
            await asyncio.sleep(1)
            print(f"  ✅ Filled SQL: {SQL_QUERY[:50]}")

            # Fill step name
            await page.evaluate('''() => {
                const field = Ext.getCmp('textfield-1247');
                if (field) field.setValue('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("  ❌ Save button not found")
        else:
            print("  ❌ No SQL textarea found")
            await page.screenshot(path="/tmp/v16_no_sql.png")

        # Print final state
        print(f"\n=== Final 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())
