"""Automated Playwright browser test for Project CRUD, WBS Hierarchy & AI Timeline decomposition."""

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 Project & WBS 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 DSConsE2E",
        )
        page = await context.new_page()
        page.on("console", lambda msg: print(f"[CONSOLE] {msg.type}: {msg.text}"))
        page.on("pageerror", lambda err: print(f"[PAGEERROR] {err}"))

        # Step 1: Login
        print("\n[TEST 1/6] 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)
        await page.wait_for_timeout(1000)
        print(f"  -> Successfully authenticated. Current URL: {page.url}", flush=True)

        # Step 2: Navigate to Projects & WBS (/dashboard/projects)
        print("\n[TEST 2/6] Navigating to /dashboard/projects...", flush=True)
        await page.goto(f"{BASE_URL}/dashboard/projects", wait_until="networkidle")
        await page.wait_for_timeout(1500)

        # Verify KPI values loaded
        kpi_total = await page.inner_text("#kpi-total-projects")
        kpi_val = await page.inner_text("#kpi-total-value")
        print(
            f"  -> KPI Metrics: Total Projects={kpi_total}, Total Contract Value={kpi_val}",
            flush=True,
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "wbs_01_projects_hub.png"))

        # Step 3: Open Create Project Modal and Run AI WBS Decomposition Workflow
        print(
            "\n[TEST 3/6] Testing AI WBS Decomposition Workflow in Modal...", flush=True
        )
        await page.click("button:has-text('+ Thêm Dự Án Mới')")
        await page.wait_for_selector(
            "#modal-project-form", state="visible", timeout=3000
        )

        # Fill project basic info
        test_proj_code = (
            f"DA-TEST-AUTO-{int(asyncio.get_event_loop().time() * 1000) % 10000}"
        )
        await page.fill("#form-project-code", test_proj_code)
        await page.fill("#form-project-name", "Trường Mầm Non Xã Tân Lập")
        await page.fill("#form-client-name", "Ban QLDA Huyện Vũ Thư")
        await page.fill("#form-location", "Thái Bình")
        await page.fill("#form-contract-value", "6200000000")
        await page.fill("#form-budget-amount", "5800000000")
        await page.fill("#form-contract-number", "12/2026/HĐXD-TL")
        await page.fill("#form-duration-days", "150")

        # Enter contract price schedule text for AI
        contract_text = "1. Đào đất & móng băng bê tông cốt thép: 450 m3\n2. Xây tường và kết cấu khung 2 tầng: 1200 m2\n3. Hoàn thiện sơn bả & thiết bị điện nước M&E"
        await page.fill("#form-contract-schedule-text", contract_text)
        await page.wait_for_timeout(300)

        # Trigger AI decomposition
        print("  -> Clicking 'AI Phân Rã Tiến Độ Ngay' button...", flush=True)
        await page.click("button:has-text('AI Phân Rã Tiến Độ Ngay')")
        await page.wait_for_selector("#modal-ai-preview", state="visible", timeout=5000)
        await page.wait_for_timeout(1000)

        ai_preview_text = await page.inner_text("#modal-ai-preview")
        print(f"  -> AI Decomposition Result: {ai_preview_text[:120]}...", flush=True)
        assert (
            "Đã phân rã thành công" in ai_preview_text
            or "hạng mục WBS" in ai_preview_text
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "wbs_02_modal_ai_preview.png"))

        # Submit form to create project
        print("  -> Submitting Project Create Form...", flush=True)
        await page.click("#form-submit-btn")
        await page.wait_for_selector(
            "#modal-project-form", state="hidden", timeout=5000
        )
        await page.wait_for_timeout(1500)

        # Step 4: Verify Project in Table and Open Project Detail Center
        print(
            "\n[TEST 4/6] Verifying project created and opening Project Detail Center...",
            flush=True,
        )
        table_html = await page.inner_text("#projects-table-body")
        assert test_proj_code in table_html or "Trường Mầm Non" in table_html
        print(
            f"  -> Project {test_proj_code} successfully listed in table!", flush=True
        )
        await page.screenshot(path=str(SCREENSHOT_DIR / "wbs_03_project_listed.png"))

        # Click on project code to view detail
        await page.click(f"span:has-text('{test_proj_code}')")
        await page.wait_for_selector(
            "#view-project-detail", state="visible", timeout=5000
        )
        await page.wait_for_timeout(1000)

        # Verify Detail Header
        detail_name = await page.inner_text("#detail-project-name")
        print(f"  -> Landed in Detail View of: {detail_name}", flush=True)
        assert "Trường Mầm Non" in detail_name
        await page.screenshot(path=str(SCREENSHOT_DIR / "wbs_04_detail_overview.png"))

        # Step 5: Test Tab Navigation in Detail Center (Timeline/Gantt & WBS Tree)
        print(
            "\n[TEST 5/6] Testing Detail Sub-tabs: Timeline & WBS Hierarchy...",
            flush=True,
        )

        # Tab 2: Timeline
        await page.click("button:has-text('Timeline & Biểu Đồ Gantt')")
        await page.wait_for_timeout(500)
        milestone_nodes = await page.query_selector_all(".timeline-node")
        print(
            f"  -> Timeline Milestones rendered: {len(milestone_nodes)} milestones",
            flush=True,
        )
        assert len(milestone_nodes) >= 4
        await page.screenshot(path=str(SCREENSHOT_DIR / "wbs_05_detail_timeline.png"))

        # Tab 3: WBS Hierarchy
        await page.click("button:has-text('Cây Phân Rã WBS & Việc Cần Làm')")
        await page.wait_for_timeout(500)
        wbs_phases = await page.query_selector_all(".wbs-phase-block")
        wbs_tasks = await page.query_selector_all(".wbs-task-row")
        print(
            f"  -> WBS Hierarchy rendered: {len(wbs_phases)} Phases, {len(wbs_tasks)} Tasks",
            flush=True,
        )
        assert len(wbs_phases) == 4
        assert len(wbs_tasks) >= 10
        await page.screenshot(path=str(SCREENSHOT_DIR / "wbs_06_detail_wbs_tree.png"))

        # Step 6: Quick Task Progress Toggle & Return to list
        print(
            "\n[TEST 6/6] Testing Quick WBS Complete toggle and navigation back...",
            flush=True,
        )
        toggle_btn = await page.query_selector(".wbs-task-row button")
        if toggle_btn:
            await toggle_btn.click()
            await page.wait_for_timeout(1000)
            print("  -> Toggled task completion status successfully!", flush=True)

        await page.click("button:has-text('Quay lại Danh Sách Dự Án')")
        await page.wait_for_selector(
            "#view-project-list", state="visible", timeout=3000
        )
        await page.wait_for_timeout(500)
        print("  -> Successfully returned to Projects List View.", flush=True)

        await browser.close()
        print(
            "\n[SUCCESS] All Project CRUD & WBS Browser E2E Tests PASSED 100%!",
            flush=True,
        )


if __name__ == "__main__":
    asyncio.run(run())
