"""Comprehensive Playwright automation test script verifying the redesigned invoice detail modal,
clean signature formatting, auto text-wrapping, and interactive column resizing.
"""

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_redesigned_modal_and_resizing():
    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()

        # 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)

        # Step 2: Go to 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)

        # Step 3: Switch to Output Tab
        tab_out = page.locator("#preset-output")
        if await tab_out.count() > 0:
            await tab_out.click()
            await page.wait_for_timeout(1200)

        # Click the first output invoice row
        first_row = page.locator("tr.invoice-row-clickable").first
        await first_row.click()
        await page.wait_for_timeout(2000)

        # Step 4: Screenshot initial clean modal view
        p1 = ARTIFACTS_DIR / "redesigned_clean_invoice_modal.png"
        await page.screenshot(path=str(p1))
        print(f"[3] Saved initial redesigned modal screenshot: {p1}")

        # Step 5: Simulate interactive column resizing on column 2 (Tên Hàng Hóa)
        resizers = page.locator(".col-resizer")
        count = await resizers.count()
        print(f"[4] Found {count} interactive column resizers.")
        if count >= 2:
            resizer_2 = resizers.nth(1)  # resizer for item name column
            box = await resizer_2.bounding_box()
            if box:
                start_x = box["x"] + box["width"] / 2
                start_y = box["y"] + box["height"] / 2

                # Perform mousedown, mousemove (+120px to widen), mouseup
                await page.mouse.move(start_x, start_y)
                await page.mouse.down()
                await page.mouse.move(start_x + 120, start_y, steps=10)
                await page.mouse.up()
                await page.wait_for_timeout(1000)
                print("[5] Successfully dragged column resizer (+120px).")

        # Step 6: Screenshot modal after column widening
        p2 = ARTIFACTS_DIR / "invoice_modal_column_resized.png"
        await page.screenshot(path=str(p2))
        print(f"[6] Saved resized column screenshot: {p2}")

        # Step 7: Scroll modal content to capture bottom financial summary and clean signature seal
        modal_content = page.locator("#detail-modal .modal-content")
        await modal_content.evaluate("el => el.scrollTop = el.scrollHeight")
        await page.wait_for_timeout(1000)

        p3 = ARTIFACTS_DIR / "invoice_modal_bottom_summary_seal.png"
        await page.screenshot(path=str(p3))
        print(f"[7] Saved bottom financial summary screenshot: {p3}")

        await browser.close()
        print(
            "[SUCCESS] All Playwright modal verification steps completed successfully!"
        )


if __name__ == "__main__":
    asyncio.run(test_redesigned_modal_and_resizing())
