"""Playwright browser verification for category filter pills and linked equipment on invoices dashboard."""

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")
ARTIFACTS_DIR = Path(
    r"C:\Users\Admin\.gemini\antigravity-ide\brain\7a484f5f-1abe-4f97-84de-ac6b53252110"
)


async def test_invoices_category_ui():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width": 1440, "height": 960})
        page = await context.new_page()

        page.on("dialog", lambda dialog: asyncio.create_task(dialog.accept()))

        # Step 1: Login
        print("[1] Logging in...")
        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(800)

        # Step 2: Open Invoices Dashboard
        print("[2] Navigating to Invoices Dashboard...")
        await page.goto(f"{BASE_URL}/dashboard/invoices", wait_until="networkidle")
        await page.wait_for_timeout(1500)

        p_inv_main = ARTIFACTS_DIR / "invoices_category_pills_kpi_verified.png"
        await page.screenshot(path=str(p_inv_main))
        print(f"[2] Saved Invoices Category Pills screenshot: {p_inv_main}")

        # Step 3: Click 'Xe Máy & Thiết Bị' filter pill
        print("[3] Clicking Xe Máy & Thiết Bị filter pill...")
        mach_pill = page.locator("#cat-pill-machinery")
        if await mach_pill.count() > 0:
            await mach_pill.first.click()
            await page.wait_for_timeout(1200)

        p_mach_invoices = ARTIFACTS_DIR / "invoices_filtered_machinery_verified.png"
        await page.screenshot(path=str(p_mach_invoices))
        print(f"[3] Saved Filtered Machinery Invoices screenshot: {p_mach_invoices}")

        # Step 4: Open first invoice modal to verify linked equipment
        print("[4] Opening invoice detail modal...")
        first_row = page.locator("#invoices-tbody tr").first
        if await first_row.count() > 0:
            await first_row.click()
            await page.wait_for_timeout(1500)

        p_modal = ARTIFACTS_DIR / "invoices_modal_linked_equipment_verified.png"
        await page.screenshot(path=str(p_modal))
        print(f"[4] Saved Invoice Modal Linked Equipment screenshot: {p_modal}")

        await browser.close()
        print("[SUCCESS] All Invoices Category & Linked Equipment UI tests passed!")


if __name__ == "__main__":
    asyncio.run(test_invoices_category_ui())
