import asyncio
import re
from playwright import async_api
from playwright.async_api import expect

async def run_test():
    pw = None
    browser = None
    context = None

    try:
        # Start a Playwright session in asynchronous mode
        pw = await async_api.async_playwright().start()

        # Launch a Chromium browser in headless mode with custom arguments
        browser = await pw.chromium.launch(
            headless=True,
            args=[
                "--window-size=1280,720",
                "--disable-dev-shm-usage",
                "--ipc=host",
                "--single-process"
            ],
        )

        # Create a new browser context (like an incognito window)
        context = await browser.new_context()
        # Wider default timeout to match the agent's DOM-stability budget;
        # auto-waiting Playwright APIs (expect, locator.wait_for) inherit this.
        context.set_default_timeout(15000)

        # Open a new page in the browser context
        page = await context.new_page()

        # Interact with the page elements to simulate user flow
        # -> navigate
        await page.goto("http://localhost:8890/login")
        try:
            await page.wait_for_load_state("domcontentloaded", timeout=5000)
        except Exception:
            pass
        
        # -> Fill the email field with admin@example.com (then fill password and click Sign in).
        # email input placeholder="agent@example.com"
        elem = page.locator("xpath=/html/body/div/div/div/div[2]/div[2]/form/div/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("admin@example.com")
        
        # -> Fill the email field with admin@example.com (then fill password and click Sign in).
        # password input placeholder="••••••••"
        elem = page.locator("xpath=/html/body/div/div/div/div[2]/div[2]/form/div[2]/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("Admin123!")
        
        # -> Fill the email field with admin@example.com (then fill password and click Sign in).
        # button "Sign in"
        elem = page.locator("xpath=/html/body/div/div/div/div[2]/div[2]/form/button").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Open the AI agents admin page by clicking the 'AI agents' link in the Admin sidebar.
        # link "AI agents"
        elem = page.locator("xpath=/html/body/div/div/aside/nav/a[8]").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Open the create agent form by clicking the 'New agent' button.
        # button "New agent"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div/button").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Fill the Display name field for the new agent.
        # text input
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("localhost.PRD Agent")
        
        # -> Fill the Display name field for the new agent.
        # password input placeholder="Required for new agents"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[3]/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("sk-test-localhost-000")
        
        # -> Fill the Display name field for the new agent.
        # Fill the Display name field for the new agent.
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[5]/textarea").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("Assistant for the localhost PRD test \u2014 answer support questions concisely and reference allowed KB topics only when applicable.")
        
        # -> Fill the Display name field for the new agent.
        # checkbox input
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[6]/ul/li/label/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Fill the Display name field for the new agent.
        # button "Cancel"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[3]/button").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Open the 'New agent' modal so the create form can be filled and then submit it.
        # button "New agent"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div/button").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Fill the create-agent form (display name, API key, persona), select at least one knowledge topic, then submit the form by clicking Create.
        # text input
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("localhost.PRD Agent")
        
        # -> Fill the create-agent form (display name, API key, persona), select at least one knowledge topic, then submit the form by clicking Create.
        # password input placeholder="Required for new agents"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[3]/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("sk-test-localhost-000")
        
        # -> Fill the create-agent form (display name, API key, persona), select at least one knowledge topic, then submit the form by clicking Create.
        # Fill the create-agent form (display name, API key, persona), select at least one knowledge topic, then submit the form by clicking Create.
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[5]/textarea").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("Assistant for the localhost PRD test \u2014 answer support questions concisely and reference allowed KB topics only when applicable.")
        
        # -> Fill the create-agent form (display name, API key, persona), select at least one knowledge topic, then submit the form by clicking Create.
        # button "Cancel"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[3]/button").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Open the 'New agent' modal by clicking the + New agent button so the create form can be filled.
        # button "New agent"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div/button").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Fill the Display name, API key, Persona, select a knowledge topic checkbox, then click Create to submit the new agent.
        # text input
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("localhost.PRD Agent")
        
        # -> Fill the Display name, API key, Persona, select a knowledge topic checkbox, then click Create to submit the new agent.
        # password input placeholder="Required for new agents"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[3]/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("sk-test-localhost-000")
        
        # -> Fill the Display name, API key, Persona, select a knowledge topic checkbox, then click Create to submit the new agent.
        # Fill the Display name, API key, Persona, select a knowledge topic checkbox, then click Create to submit the new agent.
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[5]/textarea").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.fill("Assistant for the localhost PRD test \u2014 answer support questions concisely and reference allowed KB topics only when applicable.")
        
        # -> Fill the Display name, API key, Persona, select a knowledge topic checkbox, then click Create to submit the new agent.
        # checkbox input
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[2]/form/div[6]/ul/li/label/input").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # -> Click the Create button to submit the new agent form, then verify the new agent appears in the Catalog.
        # button "Create"
        elem = page.locator("xpath=/html/body/div/div/div/main/div/div[3]/div[2]/div[3]/button[2]").nth(0)
        await elem.wait_for(state="visible", timeout=10000)
        await elem.click()
        
        # --> Test passed — verified by AI agent
        frame = context.pages[-1]
        current_url = await frame.evaluate("() => window.location.href")
        assert current_url is not None, "Test completed successfully"
        await asyncio.sleep(5)

    finally:
        if context:
            await context.close()
        if browser:
            await browser.close()
        if pw:
            await pw.stop()

asyncio.run(run_test())
    