import asyncio
import os
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 = os.environ.get("TEST_BASE_URL", "http://127.0.0.1:8000")
ARTIFACTS_DIR = Path(
    r"C:\Users\Admin\.gemini\antigravity-ide\brain\1792ecf6-90bc-4f3d-b8ab-2b680d6b356b"
)
ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)


async def run_browser_verification():
    print(
        f"[TEST] Starting Comprehensive Machinery & E-Invoice Browser 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": 1600, "height": 1000},
            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 DSConsMachineryE2E",
        )
        page = await context.new_page()
        page.on("dialog", lambda dialog: dialog.accept())

        # ----------------------------------------------------------------------
        # 1. Login Authentication
        # ----------------------------------------------------------------------
        print("\n[STEP 1/5] Authenticating as SuperAdmin...", flush=True)
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle", timeout=30000)
        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)

        # ----------------------------------------------------------------------
        # 2. Navigate to Invoices Dashboard (/dashboard/invoices)
        # ----------------------------------------------------------------------
        print("\n[STEP 2/5] Navigating to E-Invoices Dashboard...", flush=True)
        await page.goto(
            f"{BASE_URL}/dashboard/invoices", wait_until="networkidle", timeout=30000
        )
        await page.wait_for_timeout(2000)

        # Check KPIs
        kpi_input = await page.inner_text("#kpi-input-total")
        kpi_eq_total = await page.inner_text("#kpi-equipment-total")
        kpi_eq_count = await page.inner_text("#kpi-equipment-count")
        print(f"  -> Input Total: {kpi_input}", flush=True)
        print(f"  -> Equipment Assets KPI: {kpi_eq_total} ({kpi_eq_count})", flush=True)

        ss1_path = ARTIFACTS_DIR / "01_invoices_dashboard_category_pills.png"
        await page.screenshot(path=str(ss1_path), full_page=True)
        print(f"  -> Screenshot saved: {ss1_path}", flush=True)

        # ----------------------------------------------------------------------
        # 3. Filter by '🚜 Xe Máy & Thiết Bị' Pill
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 3/5] Testing Category Filter '🚜 Xe Máy & Thiết Bị'...", flush=True
        )
        mach_pill = page.locator("#cat-pill-machinery")
        await mach_pill.click()
        await page.wait_for_timeout(2000)

        rows = page.locator("#invoices-table-body tr.invoice-row-clickable")
        row_count = await rows.count()
        print(f"  -> Loaded {row_count} machinery invoices in table view.", flush=True)
        assert row_count > 0, "No machinery invoices found in table view!"

        ss2_path = ARTIFACTS_DIR / "02_invoices_machinery_filtered.png"
        await page.screenshot(path=str(ss2_path), full_page=True)
        print(f"  -> Screenshot saved: {ss2_path}", flush=True)

        # ----------------------------------------------------------------------
        # 4. Open Invoice Detail Modal & Verify Linked Equipment
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 4/5] Opening Invoice Detail Modal & Verifying Equipment...",
            flush=True,
        )
        first_row = rows.first
        await first_row.click()
        await page.wait_for_timeout(2000)

        modal = page.locator("#detail-modal.active")
        assert await modal.count() > 0, "Detail modal did not open!"
        print("  -> Detail modal opened successfully.", flush=True)

        ss3_path = ARTIFACTS_DIR / "03_invoice_detail_modal_with_equipment.png"
        await page.screenshot(path=str(ss3_path), full_page=True)
        print(f"  -> Screenshot saved: {ss3_path}", flush=True)

        # Close Modal
        await page.locator("#detail-modal .modal-close").click()
        await page.wait_for_timeout(800)

        # Test Materials Filter
        print("  -> Testing Category Filter '🧱 Vật Tư Xây Dựng'...", flush=True)
        await page.locator("#cat-pill-materials").click()
        await page.wait_for_timeout(1500)
        ss4_path = ARTIFACTS_DIR / "04_invoices_materials_filtered.png"
        await page.screenshot(path=str(ss4_path), full_page=True)
        print(f"  -> Screenshot saved: {ss4_path}", flush=True)

        # ----------------------------------------------------------------------
        # 5. Navigate to Equipment Dashboard & Verify All Assets
        # ----------------------------------------------------------------------
        print(
            "\n[STEP 5/5] Navigating to Equipment & Fleet Dashboard (/dashboard/equipment#truth)...",
            flush=True,
        )
        await page.goto(
            f"{BASE_URL}/dashboard/equipment#truth",
            wait_until="networkidle",
            timeout=30000,
        )
        await page.wait_for_timeout(2000)

        ss5_path = ARTIFACTS_DIR / "05_equipment_dashboard_truth_assets.png"
        await page.screenshot(path=str(ss5_path), full_page=True)
        print(f"  -> Screenshot saved: {ss5_path}", flush=True)

        # Also view Tab 1: Đội Máy Cơ Giới Thi Công
        print("  -> Viewing Tab 1: Đội Máy Cơ Giới Thi Công & Định Mức...", flush=True)
        await page.locator("#subtab-machinery-btn").click()
        await page.wait_for_timeout(1000)

        ss6_path = ARTIFACTS_DIR / "06_equipment_dashboard_machinery_tab.png"
        await page.screenshot(path=str(ss6_path), full_page=True)
        print(f"  -> Screenshot saved: {ss6_path}", flush=True)

        await browser.close()
        print(
            "\n[SUCCESS] All Playwright browser E2E tests and screenshots completed perfectly!",
            flush=True,
        )


if __name__ == "__main__":
    asyncio.run(run_browser_verification())
