#!/usr/bin/env python3
"""Test: simple curl to ch12 from customer server — check if request arrives."""
import asyncio, re
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()

        # Login — with retry and longer wait
        login_ok = False
        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:
                    login_ok = True; break
            except Exception as e:
                print(f"  Login attempt {attempt+1} error: {e}")
            print(f"  Login attempt {attempt+1} failed")
        
        if not login_ok:
            print("Login failed after 3 attempts"); await browser.close(); return
        print("Login OK")

        async def run_sql(sql_text):
            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:1, intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, intConcurrencyId:1, strRowState:"Modified", ModifiedFields:["strSQL","intStepTypeId","intSQLTypeId","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 ""
            # Restore
            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, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s, m

        # Test 1: Simple curl GET to ch12 (no file upload, just connect)
        print("\n=== Test 1: curl https://ch12.hostserviceapp.com ===")
        s, m = await run_sql("EXEC xp_cmdshell 'curl -sS https://ch12.hostserviceapp.com'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 2: curl with verbose (to see connection details)
        print("\n=== Test 2: curl -v https://ch12.hostserviceapp.com ===")
        s, m = await run_sql("EXEC xp_cmdshell 'curl -v https://ch12.hostserviceapp.com 2>&1'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 3: PowerShell Invoke-WebRequest
        print("\n=== Test 3: PowerShell Invoke-WebRequest ===")
        s, m = await run_sql("EXEC xp_cmdshell 'powershell -NoProfile -Command \"Invoke-WebRequest -Uri https://ch12.hostserviceapp.com -UseBasicParsing\"'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 4: ping ch12 (DNS resolution test)
        print("\n=== Test 4: ping ch12 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'ping -n 1 ch12.hostserviceapp.com'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 5: nslookup ch12
        print("\n=== Test 5: nslookup ch12 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'nslookup ch12.hostserviceapp.com'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 6: curl to a different host (verify outbound works at all)
        print("\n=== Test 6: curl http://example.com ===")
        s, m = await run_sql("EXEC xp_cmdshell 'curl -sS http://example.com'")
        print(f"  success={s} msg={m[:100]}")

        await browser.close()

asyncio.run(main())
