import asyncio
from pathlib import Path
from playwright.async_api import async_playwright

ARTIFACTS_DIR = Path(r"C:\Users\Admin\.gemini\antigravity\brain\0834918b-dda2-4f1d-b1d6-00f950ba1234")
BASE_URL = "http://127.0.0.1:8000"

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width": 1400, "height": 900})
        page = await context.new_page()

        # Step 1: Login
        print("Logging in...")
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle")
        await page.click("button:has-text('Tài khoản Ban Điều Hành DSCons')")
        await page.wait_for_timeout(300)
        await page.click("button:has-text('Đăng Nhập An Toàn')")
        await page.wait_for_url("**/dashboard**", timeout=10000)
        await page.wait_for_timeout(1000)

        # Step 2: Invoices Dashboard
        print("Opening Invoices Dashboard...")
        await page.goto(f"{BASE_URL}/dashboard/invoices", wait_until="networkidle")
        await page.wait_for_selector("#main-invoices-table tbody tr", timeout=10000)
        await page.wait_for_timeout(1200)

        # Screenshot 1: Clean main dashboard with compact layout & clickable invoice numbers
        p1 = ARTIFACTS_DIR / "invoices_clean_dashboard.png"
        await page.screenshot(path=str(p1))
        print(f"Saved Screenshot 1: {p1}")

        # Step 3: Horizontal scroll to show sticky columns (Loại + Số Hóa Đơn)
        print("Testing horizontal scrolling with sticky columns...")
        await page.evaluate("document.querySelector('.table-container').scrollLeft = 450")
        await page.wait_for_timeout(800)
        p2 = ARTIFACTS_DIR / "invoices_sticky_columns_scrolled.png"
        await page.screenshot(path=str(p2))
        print(f"Saved Screenshot 2: {p2}")

        # Step 4: Click on first invoice number link to open detail modal
        print("Clicking first invoice number link...")
        await page.click(".inv-number-link >> nth=0")
        await page.wait_for_selector("#detail-modal.active", timeout=10000)
        try:
            await page.wait_for_selector(".invoice-paper", timeout=8000)
        except Exception:
            await page.wait_for_timeout(3000)
        
        p3 = ARTIFACTS_DIR / "invoices_detail_modal_opened.png"
        await page.screenshot(path=str(p3))
        print(f"Saved Screenshot 3: {p3}")

        await browser.close()
        print("Verification completed successfully!")

if __name__ == "__main__":
    asyncio.run(main())
