import asyncio
import os
import sys

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")
ARTIFACT_DIR = (
    r"C:\Users\Admin\.gemini\antigravity-ide\brain\1792ecf6-90bc-4f3d-b8ab-2b680d6b356b"
)


async def run():
    print(
        "[TEST] Testing Streamlined Equipment Dashboard with Resizable Columns & Wrap Text...",
        flush=True,
    )
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width": 1560, "height": 950})
        page = await context.new_page()

        # 1. Login
        print("[1] Logging in 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)

        # 2. Go to Equipment Dashboard
        print("[2] Navigating to /dashboard/equipment...", flush=True)
        await page.goto(f"{BASE_URL}/dashboard/equipment", wait_until="networkidle")
        await page.wait_for_timeout(1500)

        # Check KPIs
        kpi_total = await page.inner_text("#kpi-total-machines")
        kpi_fleet = await page.inner_text("#kpi-transport-fleet")
        kpi_val = await page.inner_text("#kpi-equipment-value")
        print(
            f"  -> KPI Total: {kpi_total}, Fleet: {kpi_fleet}, Value: {kpi_val}",
            flush=True,
        )

        # Capture Tab 1 (Machinery)
        path_tab1 = os.path.join(ARTIFACT_DIR, "equip_streamlined_tab1_machinery.png")
        await page.screenshot(path=path_tab1)
        print(f"  -> Saved Tab 1 screenshot: {path_tab1}", flush=True)

        # 3. Test Column Resizing on Tab 1
        print("[3] Testing Column Resizing on Tab 1...", flush=True)
        th_first = page.locator("#table-machinery thead th").nth(0)
        resizer = th_first.locator(".col-resizer")
        box = await resizer.bounding_box()
        if box:
            await page.mouse.move(
                box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
            )
            await page.mouse.down()
            await page.mouse.move(box["x"] + 80, box["y"] + box["height"] / 2)
            await page.mouse.up()
            print("  -> Successfully dragged column resizer +80px!", flush=True)

        # 4. Switch to Tab 2 (Vehicles)
        print("[4] Switching to Tab 2 (Vehicles)...", flush=True)
        await page.click("#subtab-vehicles-btn")
        await page.wait_for_timeout(600)

        # Test live search filter on vehicles
        print("  -> Testing live search filter 'Howo'...", flush=True)
        await page.fill("#search-vehicles", "Howo")
        await page.wait_for_timeout(400)
        count_veh = await page.inner_text("#count-vehicles")
        print(f"  -> Filtered Vehicles Count: {count_veh}", flush=True)

        # Clear search
        await page.fill("#search-vehicles", "")
        await page.wait_for_timeout(300)

        path_tab2 = os.path.join(ARTIFACT_DIR, "equip_streamlined_tab2_vehicles.png")
        await page.screenshot(path=path_tab2)
        print(f"  -> Saved Tab 2 screenshot: {path_tab2}", flush=True)

        # 5. Switch to Tab 3 (Truth Assets)
        print("[5] Switching to Tab 3 (Truth Assets)...", flush=True)
        await page.click("#subtab-truth-btn")
        await page.wait_for_timeout(600)

        # Test Wrap Text Toggle on Tab 3
        print("  -> Testing Wrap Text Toggle...", flush=True)
        await page.click("#wrap-toggle-truth")
        await page.wait_for_timeout(500)

        path_tab3 = os.path.join(ARTIFACT_DIR, "equip_streamlined_tab3_truth.png")
        await page.screenshot(path=path_tab3)
        print(f"  -> Saved Tab 3 screenshot: {path_tab3}", flush=True)

        # 6. Test Column Resizing on Tab 3
        th_truth = page.locator("#table-truth thead th").nth(1)
        resizer_truth = th_truth.locator(".col-resizer")
        box_t = await resizer_truth.bounding_box()
        if box_t:
            await page.mouse.move(
                box_t["x"] + box_t["width"] / 2, box_t["y"] + box_t["height"] / 2
            )
            await page.mouse.down()
            await page.mouse.move(box_t["x"] + 80, box_t["y"] + box_t["height"] / 2)
            await page.mouse.up()
            print("  -> Successfully resized Tab 3 column +80px!", flush=True)

        await browser.close()
        print(
            "[SUCCESS] All UI optimizations, resizers, and wrap toggles verified!",
            flush=True,
        )


if __name__ == "__main__":
    asyncio.run(run())
