"""Quick login test for all accounts"""
from playwright.sync_api import sync_playwright
import time

BASE_URL = "http://localhost:3000"
ACCOUNTS = [
    ("admin", "admin@xiaoxue.edu.cn", "123456"),
    ("teacher", "t_chinese_1@xiaoxue.edu.cn", "123456"),
    ("student", "student_g1c1_1@xiaoxue.edu.cn", "123456"),
    ("parent", "parent_g1c1_1@xiaoxue.edu.cn", "123456"),
]

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    for role, email, password in ACCOUNTS:
        context = browser.new_context(viewport={"width": 1440, "height": 900}, locale="zh-CN")
        page = context.new_page()
        print(f"\n>>> Testing {role} ({email})...")
        try:
            page.goto(f"{BASE_URL}/login", timeout=30000)
            page.wait_for_load_state("networkidle", timeout=15000)
            time.sleep(1)

            email_input = page.locator('input[name="email"]')
            if email_input.count() == 0:
                email_input = page.locator('input[type="email"]')
            email_input.fill(email)

            password_input = page.locator('input[name="password"]')
            if password_input.count() == 0:
                password_input = page.locator('input[type="password"]')
            password_input.fill(password)

            # Click the submit button
            submit_btn = page.locator('button[type="submit"]')
            if submit_btn.count() == 0:
                submit_btn = page.get_by_role("button", name="Sign In with Email")
            if submit_btn.count() == 0:
                submit_btn = page.locator("button").filter(has_text="Sign In")
            
            print(f"    Found button: {submit_btn.count()}")
            submit_btn.click()

            # Wait for navigation
            try:
                page.wait_for_url(lambda url: "/login" not in url, timeout=15000)
            except Exception:
                pass
            page.wait_for_timeout(2000)

            print(f"    Final URL: {page.url}")
            if "/login" in page.url:
                print(f"    ❌ {role} login FAILED")
                # Check for error messages
                error = page.locator('[role="alert"], .error, p:has-text("error"), p:has-text("failed")')
                if error.count() > 0:
                    print(f"    Error: {error.first.text_content()}")
            else:
                print(f"    ✅ {role} login SUCCESS")
        except Exception as e:
            print(f"    ❌ {role} exception: {e}")
        finally:
            context.close()
    browser.close()
