#!/usr/bin/env python3
"""v13: Open Process 7 → modify step name via UI → Save → capture AJAX endpoint."""
import asyncio, json
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()

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

        # Record pre-save AJAX count
        pre_count = len(all_ajax)
        print(f"Pre-save AJAX: {pre_count}")

        # Modify the process name (simple change to trigger Save)
        await page.evaluate('''() => {
            const field = document.getElementById('textfield-1076-inputEl');
            if (field) {
                field.value = 'AP DPR Diagnostics';
                field.dispatchEvent(new Event('input', {bubbles: true}));
                field.dispatchEvent(new Event('change', {bubbles: true}));
            }
        }''')
        await asyncio.sleep(1)

        # Click Save button
        print("\n=== Clicking Save ===")
        save_btn = await page.query_selector('#button-1343')
        if not save_btn:
            save_btn = await page.query_selector('#button-1209')
        
        if save_btn:
            is_visible = await save_btn.is_visible()
            print(f"  Save button visible: {is_visible}")
            if is_visible:
                await save_btn.click(timeout=5000)
                await asyncio.sleep(5)
                print("  ✅ Clicked Save")
                try: await page.wait_for_load_state("networkidle", timeout=15000)
                except: pass

        # Check post-save AJAX
        post_save = all_ajax[pre_count:]
        print(f"\n=== Post-save AJAX ({len(post_save)}) ===")
        for req in post_save:
            print(f"  {req['method']} {req['path']}")
            if req['data']:
                print(f"    data: {req['data'][:300]}")

        # If no save AJAX, try selecting step then editing
        if not post_save:
            print("\n  No save AJAX — trying step selection + edit")
            
            # Use ExtJS to select step
            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)
                    print("  Clicked Edit")
            
            # Check for new window/popup
            pages = context.pages
            print(f"  Pages: {len(pages)}")
            
            # Check for new form fields
            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)});
                    }
                });
                return fields;
            }''')
            print(f"  Visible form fields: {len(form)}")
            for f in form[:15]:
                print(f"    {f['tag']} id={f['id']} type={f['type']} val={f['value'][:40]}")
            
            # Check for textareas (SQL field)
            textareas = [f for f in form if f["tag"] == "TEXTAREA"]
            print(f"  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()):
                    print(f"    🎯 SQL FIELD FOUND!")
            
            # Check ALL visible text
            visible = await page.evaluate('''() => {
                const items = [];
                document.querySelectorAll('*').forEach(el => {
                    if (el.children.length === 0 && el.textContent && el.offsetParent !== null) {
                        const t = el.textContent.trim();
                        if (t.length > 1 && t.length < 80) items.push({text: t, id: el.id||''});
                    }
                });
                return items;
            }''')
            sql_items = [m for m in visible if any(k in m["text"].lower() for k in
                ["sql", "execute", "query", "command", "connection", "type", "step"])]
            print(f"  SQL-related labels: {len(sql_items)}")
            for m in sql_items[:10]:
                print(f"    #{m['id']} '{m['text'][:40]}'")

            # Post-edit AJAX
            post_edit = all_ajax[pre_count:]
            print(f"\n  Post-edit AJAX ({len(post_edit)}):")
            for req in post_edit:
                print(f"    {req['method']} {req['path']}")
                if req['data']:
                    print(f"      data: {req['data'][:300]}")

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

asyncio.run(main())
