"""Comprehensive Playwright automation test script verifying Cash Register (MTT) e-invoice
recognition, dedicated badges, digital signature exemption under Decree 123, and smart filtering.
"""

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_mtt_invoice_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()

        # 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: Search for K26TXN
        print("[3] Searching for K26TXN...")
        search_input = page.locator("#search-input")
        await search_input.fill("K26TXN")
        await page.keyboard.press("Enter")
        await page.wait_for_timeout(1500)

        # Capture table view with MTT badges
        p_table = ARTIFACTS_DIR / "mtt_filtered_invoices_table.png"
        await page.screenshot(path=str(p_table))
        print(f"[4] Saved MTT filtered table screenshot: {p_table}")

        # Step 4: Click on the first Petrolimex invoice row
        print("[5] Opening Cash Register (MTT) Petrolimex invoice detail modal...")
        first_row = page.locator("tr.invoice-row-clickable").first
        await first_row.click()
        await page.wait_for_timeout(2000)

        # Step 5: Capture modal screenshot
        p_modal = ARTIFACTS_DIR / "mtt_cash_register_invoice_modal_verified.png"
        await page.screenshot(path=str(p_modal))
        print(f"[6] Saved MTT invoice modal screenshot: {p_modal}")

        await browser.close()
        print(
            "[SUCCESS] All MTT Playwright browser verification steps completed successfully!"
        )


if __name__ == "__main__":
    asyncio.run(test_mtt_invoice_ui())
