"""Playwright verification for user's newly integrated tabs and features."""

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_user_features():
    print(
        "\n[TEST] Starting verification of User's new tabs and workflows...", 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: Test Equipment Fuel Efficiency Tab
        print(
            "[2] Navigating to Equipment Dashboard -> Tab 4: Fuel Efficiency...",
            flush=True,
        )
        await page.goto(
            f"{BASE_URL}/dashboard/equipment#efficiency", wait_until="networkidle"
        )
        await page.wait_for_timeout(1000)

        # Switch to Tab 4 explicitly
        tab4_btn = page.locator("#subtab-efficiency-btn")
        if await tab4_btn.count() > 0:
            await tab4_btn.click()
            await page.wait_for_timeout(800)

        assert await page.locator("#tab-efficiency").is_visible(), (
            "Tab Fuel Efficiency is not visible!"
        )
        print("  -> Tab 4 (Fuel Efficiency) verified visible!", flush=True)
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "feat_01_equipment_fuel_efficiency.png")
        )
        print(
            f"  -> Saved {SCREENSHOT_DIR / 'feat_01_equipment_fuel_efficiency.png'}",
            flush=True,
        )

        # Step 3: Test Project Detail -> Tab 7: IPCs Payments Tracker
        print(
            "[3] Navigating to Projects Dashboard -> Tab 7: IPCs Payments Tracker...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/projects", wait_until="networkidle")
        await page.wait_for_timeout(1000)

        first_proj = page.locator("#projects-table-body td:first-child span").first
        await first_proj.click()
        await page.wait_for_timeout(800)

        tab_ipc_btn = page.locator(".detail-tab-btn:has-text('IPC')")
        if await tab_ipc_btn.count() > 0:
            await tab_ipc_btn.click()
            await page.wait_for_timeout(800)
            assert await page.locator("#tab-content-ipcs").is_visible(), (
                "Tab IPCs is not visible!"
            )
            print("  -> Tab 7 (IPCs Payments Tracker) verified visible!", flush=True)
            await page.screenshot(
                path=str(SCREENSHOT_DIR / "feat_02_project_ipcs_tracker.png")
            )
            print(
                f"  -> Saved {SCREENSHOT_DIR / 'feat_02_project_ipcs_tracker.png'}",
                flush=True,
            )

        # Step 4: Test Readiness Dashboard -> Gaps & Findings
        print(
            "[4] Navigating to Readiness Dashboard -> Quality Gaps & Dossier Findings...",
            flush=True,
        )
        await page.goto(f"{BASE_URL}/dashboard/readiness", wait_until="networkidle")
        await page.wait_for_timeout(1000)

        table_gaps = page.locator("#table-readiness-gaps")
        assert await table_gaps.is_visible(), "Readiness Gaps table is not visible!"
        print("  -> Dossier Review Gaps table verified visible!", flush=True)
        await page.screenshot(
            path=str(SCREENSHOT_DIR / "feat_03_readiness_dossier_gaps.png")
        )
        print(
            f"  -> Saved {SCREENSHOT_DIR / 'feat_03_readiness_dossier_gaps.png'}",
            flush=True,
        )

        await browser.close()
        print("\n[SUCCESS] All user-added tabs and features passed 100%!\n", flush=True)


if __name__ == "__main__":
    asyncio.run(test_user_features())
