#!/usr/bin/env python3
"""v17: Fill SQL via ExtJS → Save via ExtJS API (bypass click interception) → ExecuteStep."""
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 to "SQL Statement" (3)
        await page.evaluate('''() => {
            const combo = Ext.getCmp('combo-1264');
            if (combo) { combo.setValue(3); combo.fireEvent('select', combo); }
        }''')
        await asyncio.sleep(3)
        print("✅ SQL Type changed to SQL Statement")

        # Fill SQL textarea via ExtJS API
        result = await page.evaluate(f'''() => {{
            const field = Ext.getCmp('textarea-1265');
            if (field) {{
                field.setValue(`{SQL_QUERY}`);
                field.fireEvent('change', field, field.getValue());
                field.fireEvent('dirtychange', field);
                return 'SQL set: ' + field.getValue().substring(0, 50);
            }}
            return 'textarea not found';
        }}''')
        print(f"  {result}")
        await asyncio.sleep(1)

        # Fill step name
        await page.evaluate('''() => {
            const field = Ext.getCmp('textfield-1247');
            if (field) field.setValue('SQL Health Check');
        }''')
        print("  Step name set")

        # Save via ExtJS API (bypass click interception)
        print("\n=== Saving via ExtJS ===")
        pre_save = len(all_ajax)
        
        save_result = await page.evaluate('''() => {
            // Find save button component
            const btn = Ext.getCmp('button-1271');  // Save button in step editor
            if (btn) {
                btn.fireEvent('click', btn);
                return 'fired click on button-1271';
            }
            // Try alternative IDs
            const ids = ['button-1209', 'button-1343', 'button-1271'];
            for (const id of ids) {
                const b = Ext.getCmp(id);
                if (b) {
                    b.fireEvent('click', b);
                    return 'fired click on ' + id;
                }
            }
            // Try finding by text
            const buttons = Ext.ComponentQuery.query('button');
            for (const b of buttons) {
                if (b.getText && b.getText() === 'Save' && b.isVisible()) {
                    b.fireEvent('click', b);
                    return 'fired click on ' + b.id + ' (text=Save)';
                }
            }
            return 'no save button found';
        }''')
        print(f"  {save_result}")
        await asyncio.sleep(5)
        try: await page.wait_for_load_state("networkidle", timeout=10000)
        except: pass

        # 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'][:300]}")

        # If save worked, now execute the step
        if post_save:
            print("\n=== Executing Step ===")
            pre_exec = len(all_ajax)
            
            # Use ExecuteStep API directly
            exec_result = await page.evaluate('''async () => {
                const response = await fetch('/''' + APP + '''/Integration/api/Execute/ExecuteStep', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({intStepId: 9}),
                    credentials: 'include'
                });
                const data = await response.text();
                return {status: response.status, body: data.substring(0, 500)};
            }''')
            print(f"  ExecuteStep: HTTP {exec_result['status']}")
            print(f"  Body: {exec_result['body'][:300]}")

        # Also try: close step editor, then ExecuteStep
        print("\n=== Close + ExecuteStep ===")
        await page.evaluate('''() => {
            const btn = Ext.getCmp('button-1273');
            if (btn) btn.fireEvent('click', btn);
        }''')
        await asyncio.sleep(3)

        pre_exec2 = len(all_ajax)
        
        # Click Run Selected Step
        run_btn = await page.query_selector('#button-1212')
        if run_btn:
            vis = await run_btn.is_visible()
            print(f"  Run button visible: {vis}")
            if vis:
                await run_btn.click(timeout=5000)
                await asyncio.sleep(10)
                print("  ✅ Run clicked")

        post_exec2 = all_ajax[pre_exec2:]
        print(f"\n  Post-exec AJAX ({len(post_exec2)}):")
        for req in post_exec2:
            print(f"    {req['m']} {req['u']}")
            if req['d']:
                print(f"      data: {req['d'][:300]}")

        # Print final state
        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 browser.close()

asyncio.run(main())
