"""Playwright Browser Automation Verification for DSCons Cloud Parity Gate.

Verifies:
1. Subdomain redirect: https://erp.dinhsonconstruction.com -> /v1/erp/dashboard -> login redirect
2. Admin login execution with autofill: admin@dscons.vn / DSCons@2026#SecureAdmin
3. Live ERP Dashboard rendering real figures: 143 projects, 82 equipment, 128.8B VND across 1,369 invoices
4. Public portal https://dinhsonconstruction.com updated with 143+ projects, 82+ machines, and direct ERP CTA
"""

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

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

SCREENSHOT_DIR = Path("reports/browser_verification")
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)


async def main():
    print("[1/5] Khởi động trình duyệt Chromium...")
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(
            viewport={"width": 1440, "height": 900},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 DSCons-Automated-Auditor/3.0",
        )
        page = await context.new_page()

        # Step 1: Subdomain redirect test
        print("[2/5] Kiểm tra điều hướng https://erp.dinhsonconstruction.com/ ...")
        response = await page.goto("https://erp.dinhsonconstruction.com/", wait_until="networkidle", timeout=30000)
        current_url = page.url
        print(f"      URL hiện tại sau điều hướng: {current_url}")
        assert "/login" in current_url or "/dashboard" in current_url, f"Chưa vào luồng ERP: {current_url}"
        await page.screenshot(path=str(SCREENSHOT_DIR / "01_erp_subdomain_login.png"))
        print("      [OK] Đã chuyển hướng chính xác vào cổng bảo mật ERP!")

        # Step 2: Login form interaction
        print("[3/5] Thực hiện đăng nhập Ban Điều Hành DSCons...")
        quick_btn = page.locator("button:has-text('Tài khoản Ban Điều Hành DSCons')")
        if await quick_btn.count() > 0:
            await quick_btn.click()
            await asyncio.sleep(0.5)
        else:
            await page.fill("#auth-email", "admin@dscons.vn")
            await page.fill("#auth-password", "DSCons@2026#SecureAdmin")

        await page.click("#submit-btn")
        await page.wait_for_url("**/dashboard**", timeout=20000)
        print(f"      [OK] Đăng nhập thành công! Đã vào dashboard: {page.url}")

        # Step 3: Wait for live KPI figures in dashboard
        print("[4/5] Chờ dữ liệu thời gian thực từ cơ sở dữ liệu DSCons tải lên dashboard...")
        await page.wait_for_selector("#kpi-projects-count", timeout=15000)
        await asyncio.sleep(3)  # Chờ các fetch hoàn tất

        proj_text = await page.text_content("#kpi-projects-count")
        equip_text = await page.text_content("#kpi-equipment-count")
        fin_text = await page.text_content("#kpi-finance-amount")
        fin_sub = await page.text_content("#kpi-finance-subtitle")

        print(f"      KPI Dự án: {proj_text}")
        print(f"      KPI Thiết bị: {equip_text}")
        print(f"      KPI Tài chính: {fin_text}")
        print(f"      Phụ đề Hóa đơn: {fin_sub}")

        assert "143" in proj_text, f"Thiếu dữ liệu 143 dự án: {proj_text}"
        assert "82" in equip_text, f"Thiếu dữ liệu 82 thiết bị: {equip_text}"
        assert "1.369" in fin_sub or "1369" in fin_sub, f"Thiếu số lượng 1.369 hóa đơn: {fin_sub}"

        await page.screenshot(path=str(SCREENSHOT_DIR / "02_erp_live_dashboard.png"))
        print("      [OK] Trung tâm điều hành ERP hiển thị đầy đủ 100% dữ liệu thực tế!")

        # Step 4: Public corporate portal verification
        print("[5/5] Kiểm tra cổng thông tin dinhsonconstruction.com...")
        await page.goto("https://dinhsonconstruction.com/", wait_until="networkidle", timeout=30000)
        body_text = await page.text_content("body")
        assert "143+" in body_text, "Thiếu số liệu 143+ trên landing page"
        assert "82+" in body_text, "Thiếu số liệu 82+ trên landing page"
        assert "128B+" in body_text, "Thiếu số liệu 128B+ trên landing page"
        assert "AI CAD & Thẩm Tra BoQ" in body_text, "Thiếu trụ cột công nghệ AI CAD trên landing page"

        await page.screenshot(path=str(SCREENSHOT_DIR / "03_public_landing_real_scale.png"))
        print("      [OK] Cổng thông tin công ty hiển thị đầy đủ quy mô thực tế và liên kết ERP!")

        await browser.close()
        print("\n=== HOÀN TẤT KIỂM THỬ PLAYWRIGHT 100% PASSED ===")

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