"""Playwright browser verification for Interactive Gantt Chart and CPM Critical Path."""

import asyncio
import sys
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

from playwright.async_api import async_playwright

BASE_URL = "http://127.0.0.1:8000"
SCREENSHOT_DIR = Path("reports/screenshots")
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)


async def test_gantt_chart_browser():
    print(
        "\n[TEST] Starting Interactive Gantt Chart & CPM Playwright E2E verification...",
        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})
        page = await context.new_page()

        # Step 1: Login
        print("[1] Logging in as SuperAdmin...", flush=True)
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle")
        await page.fill("#auth-email", "admin@dinhsonconstruction.com")
        await page.fill("#auth-password", "DSCons@2026#SecureAdmin")
        await page.click("button[type='submit']")
        await page.wait_for_timeout(1000)

        # Step 2: Go to Projects Dashboard
        print("[2] Navigating to Projects Dashboard...", flush=True)
        await page.goto(f"{BASE_URL}/dashboard/projects", wait_until="networkidle")
        await page.wait_for_timeout(1000)

        # Step 3: Open First Project Detail
        print("[3] Opening First Project Detail View...", flush=True)
        first_proj_code = page.locator("#projects-table-body td:first-child span").first
        await first_proj_code.click()
        await page.wait_for_timeout(800)

        # Step 4: Switch to Tab 2 (Timeline & Gantt)
        print("[4] Switching to Tab 2: Timeline & Biểu Đồ Gantt...", flush=True)
        tab_timeline_btn = page.locator(".detail-tab-btn:has-text('Timeline')")
        await tab_timeline_btn.click()
        await page.wait_for_timeout(800)

        # Verify Gantt viewport is visible
        gantt_viewport = page.locator("#gantt-chart-viewport")
        assert await gantt_viewport.is_visible(), "Gantt chart viewport is not visible!"

        tasks_count = await page.locator("#gantt-tasks-list .gantt-task-row").count()
        bars_count = await page.locator("#gantt-bars-container .gantt-bar").count()
        print(
            f"  -> Gantt chart rendered successfully! Tasks count: {tasks_count}, Gantt bars: {bars_count}",
            flush=True,
        )
        assert tasks_count > 0, "No Gantt tasks rendered!"
        assert bars_count > 0, "No Gantt bars rendered!"

        # Capture Daily View
        await page.screenshot(path=str(SCREENSHOT_DIR / "gantt_01_daily_view.png"))
        print(f"  -> Saved {SCREENSHOT_DIR / 'gantt_01_daily_view.png'}", flush=True)

        # Step 5: Test Switching to Weekly View
        print("[5] Switching to Weekly View Mode...", flush=True)
        await page.click("#gantt-view-week")
        await page.wait_for_timeout(400)
        await page.screenshot(path=str(SCREENSHOT_DIR / "gantt_02_weekly_view.png"))
        print(f"  -> Saved {SCREENSHOT_DIR / 'gantt_02_weekly_view.png'}", flush=True)

        # Step 6: Test CPM Critical Path Highlight
        print("[6] Toggling CPM Critical Path Highlight...", flush=True)
        await page.click("#gantt-view-day")
        await page.wait_for_timeout(300)
        await page.click("#btn-toggle-cpm")
        await page.wait_for_timeout(400)
        await page.screenshot(path=str(SCREENSHOT_DIR / "gantt_03_cpm_highlight.png"))
        print(f"  -> Saved {SCREENSHOT_DIR / 'gantt_03_cpm_highlight.png'}", flush=True)

        # Step 7: Hover over first CPM Gantt bar
        print("[7] Hovering over Gantt Bar for interactive tooltip...", flush=True)
        first_bar = page.locator(".gantt-bar.cpm-critical").first
        if await first_bar.count() > 0:
            await first_bar.hover()
            await page.wait_for_timeout(300)

        await browser.close()
        print(
            "\n[SUCCESS] Interactive Gantt Chart & CPM Playwright E2E Passed 100%!\n",
            flush=True,
        )


if __name__ == "__main__":
    asyncio.run(test_gantt_chart_browser())
