"""Comprehensive Playwright Browser Test Suite for all DSCons ERP Sub-menus."""

import asyncio
import os
import sys
from pathlib import Path

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")
SCREENSHOT_DIR = Path("reports/screenshots")
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)


async def run():
    print(
        f"[TEST] Starting Comprehensive Master DSCons ERP Playwright E2E verification on {BASE_URL}...",
        flush=True,
    )
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(
            viewport={"width": 1440, "height": 900},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 DSConsMasterE2E",
        )
        page = await context.new_page()

        # ----------------------------------------------------------------------
        # 1. Login Authentication
        # ----------------------------------------------------------------------
        print("\n[STEP 1/7] Testing SuperAdmin Login...", 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)
        await page.wait_for_timeout(1000)
        print("  -> Authenticated successfully.", flush=True)
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_01_dashboard.png"))

        # ----------------------------------------------------------------------
        # 2. Executive Command Center (/dashboard) & AI Chatbot
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 2/7] Testing Executive Command Center & AI Specialists...",
            flush=True,
        )
        await page.wait_for_selector(
            "#budget-period-tabs", state="visible", timeout=5000
        )

        # Test Budget tabs (Day / Week / Month / Year)
        await page.click("button[data-period='week']")
        await page.wait_for_timeout(300)
        await page.click("button[data-period='month']")
        await page.wait_for_timeout(300)
        await page.click("button[data-period='year']")
        await page.wait_for_timeout(300)
        await page.click("button[data-period='day']")
        await page.wait_for_timeout(300)

        # Switch AI Agent selector (e.g. Thảo BoQ)
        await page.select_option("#chat-agent-select", "thao")
        await page.wait_for_timeout(500)
        current_agent = await page.inner_text("#current-agent-name")
        print(f"  -> Active AI Agent Chatbox: {current_agent}", flush=True)
        assert "Thảo" in current_agent
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_02_ai_chatbox.png"))

        # ----------------------------------------------------------------------
        # 3. Project Management & WBS (/dashboard/projects)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 3/7] Testing Project Management & WBS Hub (/dashboard/projects)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/projects", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        kpi_proj = await page.inner_text("#kpi-total-projects")
        print(f"  -> Projects Hub loaded. Total Projects: {kpi_proj}", flush=True)
        assert int(kpi_proj) > 0
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_03_projects_hub.png"))

        # ----------------------------------------------------------------------
        # 4. Enterprise Documents & AI Legal (/dashboard/documents)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 4/7] Testing Document Management & AI Legal (/dashboard/documents)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/documents", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        doc_header = await page.inner_text("h1")
        print(f"  -> Documents Hub loaded. Header: {doc_header}", flush=True)
        assert "Quản Lý Văn Bản" in doc_header
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_04_documents_hub.png"))

        # ----------------------------------------------------------------------
        # 5. Quality Dossier & KCS Inspection (/dashboard/readiness)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 5/7] Testing Quality Dossier & KCS Inspection (/dashboard/readiness)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/readiness", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        readiness_val = await page.inner_text("#kpi-readiness-percent")
        ipc_status = await page.inner_text("#kpi-ipc-status")
        print(
            f"  -> Quality Dossier loaded. Readiness: {readiness_val}, IPC Status: {ipc_status}",
            flush=True,
        )
        assert "94.5%" in readiness_val or "%" in readiness_val
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "master_05_quality_readiness.png")
        )

        # ----------------------------------------------------------------------
        # 6. Equipment Fleet, Machinery & HRM (/dashboard/equipment & /dashboard/employees)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 6/8] Testing Equipment Fleet, Machinery & HRM (/dashboard/equipment)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/equipment", wait_until="networkidle")
        await page.wait_for_timeout(1500)

        # Test tab switching on equipment
        await page.click("#subtab-vehicles-btn")
        await page.wait_for_timeout(500)
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "master_06_equipment_fleet.png")
        )

        await page.click("#subtab-truth-btn")
        await page.wait_for_timeout(500)
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "master_07_equipment_assets.png")
        )

        # Test HRM /dashboard/employees
        await page.goto(f"{BASE_URL}/dashboard/employees", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        hrm_kpi = await page.inner_text("#kpi-total-workforce")
        print(f"  -> HRM Dashboard loaded. Total Workforce: {hrm_kpi}", flush=True)
        assert "Cán Bộ" in hrm_kpi or "96" in hrm_kpi

        # ----------------------------------------------------------------------
        # 7. User RBAC & Security Audit (/dashboard/users)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 7/8] Testing User RBAC & Security Governance (/dashboard/users)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/users", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        user_kpi = await page.inner_text("#kpi-total-users")
        print(f"  -> User RBAC Hub loaded. Total Users: {user_kpi}", flush=True)
        assert "Tài Khoản" in user_kpi
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_08_user_rbac.png"))

        # ----------------------------------------------------------------------
        # 8. Enterprise E-Invoices & Tax Management (/dashboard/invoices)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 8/10] Testing Enterprise E-Invoices & Tax (/dashboard/invoices)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/invoices", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        kpi_input = await page.inner_text("#kpi-input-total")
        print(f"  -> Invoices Hub loaded. Total Input: {kpi_input}", flush=True)
        assert "₫" in kpi_input
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_09_invoices_hub.png"))

        # ----------------------------------------------------------------------
        # 9. Enterprise Customers Hub (/dashboard/customers)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 9/11] Testing Customers Hub (/dashboard/customers)...", flush=True
        )
        await page.goto(f"{BASE_URL}/dashboard/customers", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        cust_kpi = await page.inner_text("#kpi-customers")
        cust_rev = await page.inner_text("#kpi-customers-val")
        print(
            f"  -> Customers Hub loaded. Total Customers: {cust_kpi}, Total Revenue: {cust_rev}",
            flush=True,
        )
        assert int(cust_kpi) > 0

        # Test Resizable column drag interaction on table
        first_th = page.locator("#partners-table th").first
        resizer = first_th.locator(".resizer")
        if await resizer.count() > 0:
            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"] + 50, box["y"])
                await page.mouse.up()
                await page.wait_for_timeout(300)

        # Test Wrap Text toggle button
        await page.click("#btn-wrap-toggle")
        await page.wait_for_timeout(300)
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_10_customers_hub.png"))

        # ----------------------------------------------------------------------
        # 10. Enterprise Partners & History Hub (/dashboard/partners)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 10/11] Testing Partners & Historical Change Hub (/dashboard/partners)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/partners", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        part_kpi = await page.inner_text("#kpi-partners")
        hist_kpi = await page.inner_text("#kpi-history")
        print(
            f"  -> Partners Hub loaded. Total Partners: {part_kpi}, Entities with History: {hist_kpi}",
            flush=True,
        )
        assert int(part_kpi) > 0
        assert int(hist_kpi) > 0
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_11_partners_hub.png"))

        # Test Opening Partner Modal with Historical Timeline (e.g. click first row)
        await page.click("#partners-tbody tr:first-child")
        await page.wait_for_timeout(600)

        # Switch to History tab in modal
        await page.click("#modal-tab-history")
        await page.wait_for_timeout(400)
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "master_12_partner_history_modal.png")
        )
        await page.click("#partner-modal button:has-text('✕')")
        await page.wait_for_timeout(300)

        # ----------------------------------------------------------------------
        # 11. Enterprise Vendors & Suppliers Hub (/dashboard/vendors)
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 11/11] Testing Vendors & Suppliers Hub (/dashboard/vendors)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/vendors", wait_until="networkidle")
        await page.wait_for_timeout(1500)
        vendor_kpi = await page.inner_text("#kpi-vendors")
        vendor_val = await page.inner_text("#kpi-vendors-val")
        print(
            f"  -> Vendors Hub loaded. Total Vendors: {vendor_kpi}, Total Expense: {vendor_val}",
            flush=True,
        )
        assert int(vendor_kpi) > 0
        await page.screenshot(path=str(SCREENSHOT_DIR / "master_13_vendors_hub.png"))

        await browser.close()
        print(
            "\n[SUCCESS] ALL 11 ERP SUB-MODULES PLAYWRIGHT E2E VERIFIED 100%!\n",
            flush=True,
        )


if __name__ == "__main__":
    asyncio.run(run())
