#!/usr/bin/env python3
"""Verify: does PUT actually write strSQL to DB? 
1. PUT with strSQL='TEST_SQL_VALUE'
2. GET step to verify it's in DB
3. ExecuteStep and check msg"""
import asyncio, re, json
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")

        # Step 1: PUT with strSQL
        print("\n=== Step 1: PUT with strSQL='TEST_SQL_VALUE' ===")
        put_r = 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:"Test", 
                    intStepTypeId:1, 
                    intConnectionId:1, 
                    intSQLTypeId:3, 
                    strSQL: "SELECT CAST(@@version AS int)", 
                    intConcurrencyId:1, 
                    strRowState:"Modified", 
                    ModifiedFields:["strSQL","intStepTypeId","intSQLTypeId","intConnectionId","intStepId","intConcurrencyId","strRowState"]
                }]),
                credentials: 'include'
            });
            const text = await resp.text();
            return {status: resp.status, body: text};
        }''')
        put_body = put_r.get('body', '')
        print(f"    PUT: HTTP {put_r['status']}")
        # Check if strSQL is in response
        try:
            put_data = json.loads(put_body)
            step_data = put_data.get('data', [{}])[0] if isinstance(put_data.get('data'), list) else put_data.get('data', {})
            put_strSQL = step_data.get('strSQL', 'MISSING')
            print(f"    PUT response strSQL: {str(put_strSQL)[:100]}")
            print(f"    PUT response intStepTypeId: {step_data.get('intStepTypeId')}")
            print(f"    PUT response intConnectionId: {step_data.get('intConnectionId')}")
        except Exception as e:
            print(f"    Parse error: {e}")
            print(f"    Raw body: {put_body[:300]}")

        # Step 2: GET step to verify it's in DB
        print("\n=== Step 2: GET step/4 ===")
        get_r = await page.evaluate('''async () => {
            const resp = await fetch('/''' + APP + '''/integration/api/step/get?filter=intStepId:4', {
                method: 'GET',
                credentials: 'include'
            });
            const text = await resp.text();
            return {status: resp.status, body: text};
        }''')
        get_body = get_r.get('body', '')
        print(f"    GET: HTTP {get_r['status']}")
        try:
            get_data = json.loads(get_body)
            step_data = get_data.get('data', [{}])[0] if isinstance(get_data.get('data'), list) else get_data.get('data', {})
            get_strSQL = step_data.get('strSQL', 'MISSING')
            print(f"    GET response strSQL: {str(get_strSQL)[:100]}")
            print(f"    GET response intStepTypeId: {step_data.get('intStepTypeId')}")
            print(f"    GET response intConnectionId: {step_data.get('intConnectionId')}")
        except Exception as e:
            print(f"    Parse error: {e}")
            print(f"    Raw body: {get_body[:500]}")

        # Step 3: ExecuteStep
        print("\n=== Step 3: ExecuteStep ===")
        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};
        }''')
        exec_body = exec_r.get('body', '')
        print(f"    ExecuteStep: HTTP {exec_r['status']}")
        try:
            exec_data = json.loads(exec_body)
            success = exec_data.get('success', '?')
            message = exec_data.get('message', {})
            status_text = message.get('statusText', '') if isinstance(message, dict) else str(message)
            print(f"    success: {success}")
            print(f"    statusText: {status_text[:200]}")
        except Exception as e:
            print(f"    Parse error: {e}")
            print(f"    Raw body: {exec_body[:500]}")

        # Step 4: Try ExecuteStep with strSQL in the request body
        print("\n=== Step 4: ExecuteStep with strSQL in request ===")
        exec_r2 = 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,
                    strSQL: "SELECT CAST(@@version AS int)",
                    intStepTypeId: 1,
                    intConnectionId: 1,
                    intSQLTypeId: 3
                }),
                credentials: 'include'
            });
            const text = await resp.text();
            return {status: resp.status, body: text};
        }''')
        exec_body2 = exec_r2.get('body', '')
        print(f"    ExecuteStep2: HTTP {exec_r2['status']}")
        try:
            exec_data2 = json.loads(exec_body2)
            success2 = exec_data2.get('success', '?')
            message2 = exec_data2.get('message', {})
            status_text2 = message2.get('statusText', '') if isinstance(message2, dict) else str(message2)
            print(f"    success: {success2}")
            print(f"    statusText: {status_text2[:200]}")
        except Exception as e:
            print(f"    Parse error: {e}")
            print(f"    Raw body: {exec_body2[:500]}")

        # Cleanup
        print("\n=== Cleanup ===")
        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'
            });
        }''')
        print("    cleaned")

        await browser.close()

asyncio.run(main())
