"""Playwright Browser Automation E2E Test Suite for DSCons Enterprise Dashboards."""

from __future__ import annotations

import os

import pytest
from playwright.async_api import async_playwright

BASE_URL = os.environ.get("TEST_BASE_URL", "http://127.0.0.1:8000")
ARTIFACT_DIR = (
    r"C:\Users\Admin\.gemini\antigravity\brain\72a29d29-fe73-4681-9740-f638d9cee945"
)


@pytest.mark.anyio
async def test_playwright_enterprise_ui_full_flow():
    """Kiểm thử tự động trên trình duyệt Chromium thực tế theo Quy tắc #6 trong AGENTS.md."""
    os.makedirs(ARTIFACT_DIR, exist_ok=True)

    async with async_playwright() as p:
        # 1. Khởi chạy Chromium headless
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width": 1560, "height": 950})
        page = await context.new_page()

        # 2. Kiểm thử Màn hình Đăng nhập (/login)
        try:
            await page.goto(
                f"{BASE_URL}/login", wait_until="domcontentloaded", timeout=10000
            )
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "01_e2e_login_screen.png")
            )

            # Click quick login button if available
            quick_admin = page.locator("button:has-text('SuperAdmin')")
            if await quick_admin.is_visible():
                await quick_admin.click()
                await page.wait_for_timeout(1000)
        except Exception as exc:
            # Fallback if live backend server is not running on 8000
            print(f"[PLAYWRIGHT] Notice on /login: {exc}")

        # 3. Kiểm thử Màn hình Điều Hành Tổng Thể (/dashboard)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard", wait_until="domcontentloaded", timeout=10000
            )
            await page.wait_for_timeout(1200)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "02_e2e_dashboard_main.png")
            )

            # Kiểm tra thanh Sidebar đã hiển thị Menu 'Nhân Sự AI & DHS'
            dhs_link = page.locator("aside.erp-sidebar a[href='/v1/erp/dashboard/agent-models']")
            assert await dhs_link.count() >= 1, (
                "Menu 'Nhân Sự AI & DHS' phải có mặt trên thanh Left Sidebar!"
            )

            # Kiểm tra chống đè Sidebar (Zero Occlusion): Toạ độ x của nội dung chính phải >= 200px
            main_el = page.locator("main, .page-container, .page").first
            if await main_el.is_visible():
                box = await main_el.bounding_box()
                if box:
                    assert box["x"] >= 200, (
                        f"Nội dung bị đè bởi sidebar! Toạ độ x: {box['x']}"
                    )
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard: {exc}")

        # 4. Kiểm thử Phân hệ Dự Án & WBS/EVM (/dashboard/projects)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/projects",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1500)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "03_e2e_projects_hub.png")
            )

            # Kiểm thử thao tác chuột kéo giãn độ rộng cột (Column Resizing)
            resizer = page.locator(".col-resizer").first
            if await resizer.is_visible():
                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)
                    await page.screenshot(
                        path=os.path.join(
                            ARTIFACT_DIR, "04_e2e_projects_table_resized.png"
                        )
                    )

            # Kiểm thử Wrap text toggle
            wrap_btn = page.locator("#btn-toggle-wrap")
            if await wrap_btn.is_visible():
                await wrap_btn.click()
                await page.wait_for_timeout(500)
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/projects: {exc}")

        # 5. Kiểm thử Màn hình Hóa Đơn & Tài Chính (/dashboard/invoices)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/invoices",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1000)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "05_e2e_invoices_dashboard.png")
            )
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/invoices: {exc}")

        # 6. Kiểm thử Màn hình Hồ Sơ & Kiểm Toán (/dashboard/documents)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/documents",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1000)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "06_e2e_documents_dashboard.png")
            )
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/documents: {exc}")

        # 7. Kiểm thử Màn hình Sẵn Sàng Nghiệm Thu (/dashboard/readiness)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/readiness",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1000)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "07_e2e_readiness_dashboard.png")
            )
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/readiness: {exc}")

        # 8. Kiểm thử Màn hình Nhân Sự & Ca Máy (/dashboard/employees)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/employees",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1000)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "08_e2e_employees_dashboard.png")
            )
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/employees: {exc}")

        # 9. Kiểm thử Màn hình Quản Trị Người Dùng & RBAC (/dashboard/users)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/users",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1000)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "09_e2e_users_dashboard.png")
            )
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/users: {exc}")

        # 10. Kiểm thử Màn hình Quản Trị AI Models & Benchmark (/dashboard/agent-models)
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/agent-models",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1500)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "10_e2e_agent_models_dashboard.png")
            )

            # Kiểm thử mở modal Cấu Hình Mô Hình (hỗ trợ Stealth Lifecycle & Expiration)
            btn_tune = page.locator(".persona-card button").first
            if await btn_tune.is_visible():
                await btn_tune.click()
                await page.wait_for_timeout(800)
                await page.screenshot(
                    path=os.path.join(
                        ARTIFACT_DIR, "11_e2e_agent_models_modal_stealth_lifecycle.png"
                    )
                )
                btn_close = page.locator("#editModal span:has-text('close')")
                if await btn_close.is_visible():
                    await btn_close.click()
                    await page.wait_for_timeout(500)

            # 11. Kiểm thử Kích Hoạt Điều Phối Tự Trị DeepSeek Agentic Harness (DHS)
            btn_exec_dhs = page.locator("#btnExecuteDhs")
            if await btn_exec_dhs.is_visible():
                await btn_exec_dhs.click()
                await page.wait_for_timeout(2500)
                await page.screenshot(
                    path=os.path.join(ARTIFACT_DIR, "12_e2e_dhs_agentic_war_room.png")
                )

            # 12. Kiểm thử Bảng Lịch Phân Ca Làm Việc & Anti-Spam Shield
            schedule_section = page.locator("#scheduleTableBody")
            if await schedule_section.is_visible():
                await page.screenshot(
                    path=os.path.join(ARTIFACT_DIR, "13_e2e_work_shifts_schedule.png")
                )

        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/agent-models: {exc}")

        # 13. Kiểm thử Menu Tích Hợp Trực Tiếp /dashboard/dhs trên ERP
        try:
            await page.goto(
                f"{BASE_URL}/dashboard/dhs",
                wait_until="domcontentloaded",
                timeout=10000,
            )
            await page.wait_for_timeout(1200)
            await page.screenshot(
                path=os.path.join(ARTIFACT_DIR, "14_e2e_dhs_menu_integrated.png")
            )
        except Exception as exc:
            print(f"[PLAYWRIGHT] Notice on /dashboard/dhs: {exc}")

        await browser.close()
