"""Playwright Browser E2E verification for Advanced BIM 4D/5D, EVM S-Curve, and Voice-to-Diary."""

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 Advanced Features Browser E2E 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 DSConsAdvE2E",
        )
        page = await context.new_page()

        # Step 1: Login
        print("\n[STEP 1/5] Authenticating 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)

        # Step 2: Open Project Detail Center
        print(
            "\n[STEP 2/5] Navigating to Projects Hub & Opening Detail Center...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/projects", wait_until="networkidle")
        await page.wait_for_timeout(1500)

        # Click on project code to open detail view
        await page.click("span:has-text('PILOT-NAM-HK-2026')")
        await page.wait_for_selector(
            "#view-project-detail", state="visible", timeout=5000
        )
        await page.wait_for_timeout(1000)

        # Step 3: Web-BIM 4D/5D Tab
        print(
            "\n[STEP 3/5] Testing Web-BIM 4D/5D Interactive Canvas & 4D Slider...",
            flush=True,
        )
        await page.click("button:has-text('Mô Hình 3D Web-BIM')")
        await page.wait_for_timeout(800)

        # Change 4D Time Slider
        await page.evaluate(
            "document.getElementById('bim-time-slider').value = 120; onBimSliderChange(120);"
        )
        slider_label = await page.inner_text("#bim-day-label")
        print(f"  -> 4D Slider updated: {slider_label}", flush=True)

        # Select Foundation element (BIM-FND-002)
        await page.evaluate("selectBimElement('BIM-FND-002')")
        await page.wait_for_timeout(500)
        inspector_text = await page.inner_text("#bim-inspector-content")
        print(f"  -> 5D Inspector: {inspector_text[:80]}...", flush=True)
        assert "BIM-FND-002" in inspector_text
        await page.screenshot(path=str(SCREENSHOT_DIR / "advanced_01_bim_4d_5d.png"))

        # Step 4: EVM S-Curve & IPC Generation Modal
        print("\n[STEP 4/5] Testing EVM Cost Analytics & S-Curve...", flush=True)
        await page.click("button:has-text('Quản Trị Chi Phí EVM')")
        await page.wait_for_timeout(800)

        cpi_val = await page.inner_text("#evm-cpi-val")
        spi_val = await page.inner_text("#evm-spi-val")
        print(f"  -> EVM Indexes: CPI={cpi_val}, SPI={spi_val}", flush=True)
        assert float(cpi_val) > 0
        await page.screenshot(path=str(SCREENSHOT_DIR / "advanced_02_evm_scurve.png"))

        # Test IPC Modal
        print("  -> Testing AI FIDIC IPC Assembly Modal...", flush=True)
        await page.click("button:has-text('AI Xuất Hồ Sơ IPC FIDIC')")
        await page.wait_for_selector(
            "#modal-generate-ipc", state="visible", timeout=5000
        )
        await page.wait_for_selector(
            "#modal-ipc-body-content:has-text('CHỨNG CHỈ')", timeout=5000
        )
        modal_content = await page.inner_text("#modal-ipc-body-content")
        print(f"  -> IPC Modal summary: {modal_content[:100]}...", flush=True)
        assert "CHỨNG CHỈ" in modal_content or "GIẢI NGÂN" in modal_content
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "advanced_03_ipc_fidic_modal.png")
        )
        await page.click("button:has-text('✕ Đóng')")
        await page.wait_for_timeout(500)

        # Step 5: Voice-to-Diary
        print(
            "\n[STEP 5/5] Testing AI Voice-to-Diary on Site Logs (/dashboard/employees)...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/employees", wait_until="networkidle")
        await page.wait_for_timeout(1500)

        await page.click("button:has-text('Nhật Ký Thi Công Điện Tử Hàng Ngày')")
        await page.wait_for_timeout(500)

        await page.click("button:has-text('AI Ghi Nhật Ký Giọng Nói')")
        await page.wait_for_selector(
            "#modal-voice-diary", state="visible", timeout=5000
        )
        await page.wait_for_timeout(500)

        # Handle dialog popup automatically
        page.on("dialog", lambda dialog: dialog.accept())

        await page.click("#btn-submit-voice")
        await page.wait_for_timeout(1500)

        weather_text = await page.inner_text("#diary-view-weather")
        workforce_text = await page.inner_text("#diary-view-workforce")
        print(f"  -> Updated Site Diary: {weather_text} | {workforce_text}", flush=True)
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "advanced_04_voice_to_diary.png")
        )

        await browser.close()
        print(
            "\n[SUCCESS] ALL ADVANCED FEATURES PLAYWRIGHT E2E VERIFIED 100%!",
            flush=True,
        )


if __name__ == "__main__":
    asyncio.run(run())
