import os
import sys
import time
from playwright.sync_api import sync_playwright

PORT = 5000
BASE_URL = f"http://localhost:{PORT}/static/index.html"
SCREENSHOT_DIR = "e2e_screenshots"

if not os.path.exists(SCREENSHOT_DIR):
    os.makedirs(SCREENSHOT_DIR)

def test_report_agent_e2e():
    print(f"Starting E2E Test on {BASE_URL}...")
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()

        try:
            # 1. Navigate to chatbot
            print("Navigating to Chatbot UI...")
            page.goto(BASE_URL, timeout=10000)
            page.screenshot(path=f"{SCREENSHOT_DIR}/01_initial_load.png")

            # 2. Find input box and type a prompt
            # Usually the input box is a textarea or input with placeholder or specific ID.
            # Assuming standard chatbot UI, let's look for textarea or input.
            print("Typing report prompt...")
            # We might need to wait for the UI to fully load. 
            time.sleep(2) 
            
            # Use broad selector for the chat input
            chat_input = page.locator("textarea, input[type='text']").last
            chat_input.wait_for(state="visible", timeout=5000)
            
            test_prompt = "Tạo báo cáo doanh thu test"
            chat_input.fill(test_prompt)
            page.screenshot(path=f"{SCREENSHOT_DIR}/02_filled_input.png")

            # 3. Submit
            print("Submitting prompt...")
            chat_input.press("Enter")
            
            # Some UI might need a click on a send button if Enter doesn't work.
            # send_btn = page.locator("button").filter(has_text="Send")
            # if send_btn.count() > 0: send_btn.click()

            page.screenshot(path=f"{SCREENSHOT_DIR}/03_submitted.png")

            # 4. Wait for report generation to finish
            print("Waiting for report generation (this might take 30-60s)...")
            
            # Wait for something that indicates completion, e.g., the report container or a specific text.
            # Since we don't know the exact DOM, we will wait for network idle or a timeout.
            # Let's wait for the response to stream completely.
            time.sleep(15) # Wait for initial streaming to start
            page.screenshot(path=f"{SCREENSHOT_DIR}/04_streaming.png")
            
            # Wait longer for completion
            time.sleep(30)
            page.screenshot(path=f"{SCREENSHOT_DIR}/05_completed.png")

            print("E2E Test finished successfully. Screenshots saved.")
        except Exception as e:
            print(f"E2E Test Failed: {e}")
            page.screenshot(path=f"{SCREENSHOT_DIR}/error_state.png")
            sys.exit(1)
        finally:
            browser.close()

if __name__ == "__main__":
    test_report_agent_e2e()
