#!/usr/bin/env python3
"""Check if step 4 has intConnectionId set, and try setting it explicitly."""
import asyncio, re, time
from playwright.async_api import async_playwright

IP = "74.208.83.171"
APP = "RTROGERSUAP1"

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await context.new_page()

        for attempt in range(3):
            await page.goto(f"http://{IP}/{APP}/login", wait_until="commit", timeout=30000)
            await asyncio.sleep(5)
            try:
                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(15)
                try: await page.wait_for_load_state("networkidle", timeout=20000)
                except: pass
                if "login" not in page.url.lower() or "#home" in page.url:
                    break
            except Exception as e:
                print(f"  attempt {attempt+1}: {e}")
        else:
            print("Login failed"); await browser.close(); return
        print("Login OK")

        async def run_step(name, sql_text, step_type=1, conn_id=1):
            put = await page.evaluate('''async (sqlText) => {
                const resp = await fetch('/''' + APP + '''/integration/api/step/put/4?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:4, strStepName:"Test", intStepTypeId:''' + str(step_type) + ''', intConnectionId:''' + str(conn_id) + ''', intSQLTypeId:3, strSQL: sqlText, intConcurrencyId:1, strRowState:"Modified", ModifiedFields:["strSQL","intStepTypeId","intSQLTypeId","intConnectionId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
                return {status: resp.status};
            }''', sql_text)
            if put['status'] not in (200, 202):
                return f"put_{put['status']}", ""
            await asyncio.sleep(2)
            exec_r = await page.evaluate('''async () => {
                const resp = await fetch('/''' + APP + '''/Integration/api/Execute/ExecuteStep', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({intStepId: 4}),
                    credentials: 'include'
                });
                const text = await resp.text();
                return {status: resp.status, body: text};
            }''')
            body = exec_r.get('body', '')
            success = re.search(r'"success"\s*:\s*(true|false)', body)
            msg = re.search(r'"statusText"\s*:\s*"([^"]*)"', body)
            s = success.group(1) if success else "?"
            m = msg.group(1) if msg else ""
            print(f"    {name}: success={s} msg={m[:200]}", flush=True)
            await page.evaluate('''async () => {
                await fetch('/''' + APP + '''/integration/api/step/put/4?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:4, strSQL:null, intSQLTypeId:null, intStepTypeId:null, strStepName:null, intConnectionId:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s, m

        # Test 1: WAITFOR with connection 1 — measure time
        print("\n=== Test 1: WAITFOR 5s (conn=1) ===")
        t0 = time.time()
        await run_step("waitfor_1", "WAITFOR DELAY '00:00:05'", conn_id=1)
        t1 = time.time()
        print(f"    elapsed: {t1-t0:.1f}s")
        await asyncio.sleep(2)

        # Test 2: WAITFOR with connection 0 (no connection)
        print("\n=== Test 2: WAITFOR 5s (conn=0) ===")
        t0 = time.time()
        await run_step("waitfor_0", "WAITFOR DELAY '00:00:05'", conn_id=0)
        t1 = time.time()
        print(f"    elapsed: {t1-t0:.1f}s")
        await asyncio.sleep(2)

        # Test 3: WAITFOR 10s (conn=1)
        print("\n=== Test 3: WAITFOR 10s (conn=1) ===")
        t0 = time.time()
        await run_step("waitfor_10", "WAITFOR DELAY '00:00:10'", conn_id=1)
        t1 = time.time()
        print(f"    elapsed: {t1-t0:.1f}s")
        await asyncio.sleep(2)

        # Test 4: Invalid SQL syntax (should trigger error)
        print("\n=== Test 4: Invalid SQL ===")
        await run_step("invalid", "SELECT FROM WHERE", conn_id=1)
        await asyncio.sleep(2)

        # Test 5: Try with ysnUseCurrentDatabase=true — maybe we need different connection
        # From source: if ysnUseCurrentDatabase=true, getCS uses app's connection string
        # Let's try connection IDs 1-5
        for cid in range(1, 6):
            print(f"\n=== Test 5.{cid}: WAITFOR 3s (conn={cid}) ===")
            t0 = time.time()
            await run_step(f"waitfor_c{cid}", f"WAITFOR DELAY '00:00:03'", conn_id=cid)
            t1 = time.time()
            elapsed = t1 - t0
            print(f"    elapsed: {elapsed:.1f}s {'✅ SQL EXECUTING' if elapsed > 3 else '❌ not executing'}")
            await asyncio.sleep(1)

        # Test 6: Try Send Mail with invalid SQL — does it error?
        print("\n=== Test 6: Send Mail with invalid SQL ===")
        await run_step("sendmail_invalid", "SELECT FROM WHERE", step_type=9, conn_id=1)
        await asyncio.sleep(2)

        # Test 7: Try Send Mail with valid SQL that returns data
        print("\n=== Test 7: Send Mail with valid SQL ===")
        await run_step("sendmail_valid", "SELECT 'TEST_DATA_RETURN'", step_type=9, conn_id=1)
        await asyncio.sleep(2)

        # Test 8: Try Send Mail with divide by zero
        print("\n=== Test 8: Send Mail with 1/0 ===")
        await run_step("sendmail_divzero", "SELECT 1/0", step_type=9, conn_id=1)
        await asyncio.sleep(2)

        # Test 9: Try type 9 with invalid connection (0)
        print("\n=== Test 9: Send Mail (conn=0) ===")
        t0 = time.time()
        await run_step("sendmail_c0", "WAITFOR DELAY '00:00:03'", step_type=9, conn_id=0)
        t1 = time.time()
        print(f"    elapsed: {t1-t0:.1f}s")
        await asyncio.sleep(2)

        await browser.close()

asyncio.run(main())
