import asyncio
import os
import sys

from playwright.async_api import async_playwright

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

BASE_URL = os.environ.get("TEST_BASE_URL", "http://127.0.0.1:8000")
ARTIFACT_DIR = (
    r"C:\Users\Admin\.gemini\antigravity-ide\brain\1792ecf6-90bc-4f3d-b8ab-2b680d6b356b"
)
os.makedirs(ARTIFACT_DIR, exist_ok=True)


async def test_projects_ui():
    print(
        "[TEST] Running Playwright browser tests for Projects Hub & WBS...", flush=True
    )
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width": 1560, "height": 950})
        page = await context.new_page()

        # 1. Login as SuperAdmin
        print("[1] Logging in as SuperAdmin...", flush=True)
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle")
        await page.click("button:has-text('SuperAdmin')")
        await page.wait_for_url("**/dashboard", timeout=10000)

        # 2. Navigate to Projects Dashboard
        print("[2] Navigating to /dashboard/projects...", flush=True)
        await page.goto(f"{BASE_URL}/dashboard/projects", wait_until="networkidle")
        await page.wait_for_timeout(1500)

        # Check KPIs
        kpi_total = await page.inner_text("#kpi-total-projects")
        kpi_active = await page.inner_text("#kpi-active-projects")
        kpi_val = await page.inner_text("#kpi-total-value")
        print(
            f"  -> KPI Total: {kpi_total}, Active: {kpi_active}, Value: {kpi_val}",
            flush=True,
        )

        # Screenshot 1: Projects Hub with 8 Real Ground-Truth Projects
        path1 = os.path.join(ARTIFACT_DIR, "01_projects_hub_real_data.png")
        await page.screenshot(path=path1)
        print(f"  ✓ Saved Screenshot 1: {path1}", flush=True)

        # 3. Test Column Resizing on Projects Table
        print("[3] Testing Column Resizing...", flush=True)
        th_first = page.locator("#projects-table thead th").nth(1)
        resizer = th_first.locator(".col-resizer")
        box = await resizer.bounding_box()
        if box:
            await page.mouse.move(
                box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
            )
            await page.mouse.down()
            await page.mouse.move(box["x"] + 100, box["y"] + box["height"] / 2)
            await page.mouse.up()
            await page.wait_for_timeout(500)
            print("  ✓ Successfully dragged column resizer +100px!", flush=True)

        # Screenshot 2: Resized columns
        path2 = os.path.join(ARTIFACT_DIR, "02_projects_table_resized_columns.png")
        await page.screenshot(path=path2)
        print(f"  ✓ Saved Screenshot 2: {path2}", flush=True)

        # 4. Test Wrap Text Toggle
        print("[4] Testing Wrap Text Toggle...", flush=True)
        wrap_btn = page.locator("#btn-toggle-wrap")
        if await wrap_btn.is_visible():
            await wrap_btn.click()
            await page.wait_for_timeout(500)

        # Screenshot 3: Wrap text enabled
        path3 = os.path.join(ARTIFACT_DIR, "03_projects_table_wrap_text.png")
        await page.screenshot(path=path3)
        print(f"  ✓ Saved Screenshot 3: {path3}", flush=True)

        # 5. Open Project Detail Center for DA-DADO-PHULIEN-2026
        print(
            "[5] Opening Project Detail Center for DA-DADO-PHULIEN-2026...", flush=True
        )
        phulien_link = page.locator("text=DA-DADO-PHULIEN-2026").first
        if await phulien_link.is_visible():
            await phulien_link.click()
            await page.wait_for_timeout(1500)

        # Screenshot 4: Project Detail Center with WBS & EVM
        path4 = os.path.join(ARTIFACT_DIR, "04_project_detail_wbs_evm.png")
        await page.screenshot(path=path4)
        print(f"  ✓ Saved Screenshot 4: {path4}", flush=True)

        await browser.close()
        print("[SUCCESS] All Playwright browser tests passed successfully!", flush=True)


if __name__ == "__main__":
    asyncio.run(test_projects_ui())
