"""Playwright Real Browser Automation Test: Security Hardening & Authentication Verification.

Verifies:
1. Login page loads without prefilled credentials or preset quick-login buttons.
2. Attack simulation: Entering admin@dscons.vn / 123456 is rejected with 401 and displays clear security alert.
3. Legitimate authentication: Entering admin@dscons.vn / DSCons@2026#SecureAdmin successfully logs in and redirects to /dashboard.
4. Screenshots captured and saved to artifacts.
"""

import asyncio
import shutil
import sys
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

from playwright.async_api import async_playwright

BASE_URL = "http://127.0.0.1:8000"
REPORTS_DIR = Path("reports/screenshots")
REPORTS_DIR.mkdir(parents=True, exist_ok=True)
CONV_ID = "eeb7e766-f7b2-43fd-92ef-52b79739803b"
ARTIFACT_DIR = Path(rf"C:\Users\Admin\.gemini\antigravity\brain\{CONV_ID}")
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)


async def run_auth_verification():
    print(
        "=======================================================================",
        flush=True,
    )
    print(
        "  BẮT ĐẦU KIỂM THỬ TRÌNH DUYỆT THỰC TẾ: AN NINH XÁC THỰC & CHẶNG ĐĂNG NHẬP",
        flush=True,
    )
    print(
        "=======================================================================",
        flush=True,
    )

    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width": 1440, "height": 900})
        page = await context.new_page()

        # Step 1: Open Login Page and Inspect Clean State
        print("[1] Điều hướng đến trang đăng nhập /login...", flush=True)
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle")
        await page.wait_for_timeout(800)

        email_val = await page.input_value("#auth-email")
        pwd_val = await page.input_value("#auth-password")

        print(f"  - Giá trị trường email mặc định: '{email_val}'", flush=True)
        print(f"  - Giá trị trường mật khẩu mặc định: '{pwd_val}'", flush=True)
        assert email_val == "", "LỖI: Trường email không được để trống mặc định!"
        assert pwd_val == "", "LỖI: Trường mật khẩu không được để trống mặc định!"

        preset_count = await page.locator("button:has-text('SuperAdmin')").count()
        assert preset_count == 0, "LỖI: Nút preset thử nghiệm vẫn còn trên giao diện!"
        print(
            "  -> Xác nhận: Không còn thông tin mật khẩu hay nút preset lộ lọt trên UI.",
            flush=True,
        )

        shot1 = REPORTS_DIR / "auth_01_clean_login_screen.png"
        await page.screenshot(path=str(shot1))
        shutil.copy(shot1, ARTIFACT_DIR / "auth_01_clean_login_screen.png")
        print("  📸 Đã chụp: auth_01_clean_login_screen.png", flush=True)

        # Step 2: Simulate Attack with Old Insecure Password 123456
        print("[2] Mô phỏng đăng nhập bằng mật khẩu cũ 123456...", flush=True)
        await page.fill("#auth-email", "admin@dscons.vn")
        await page.fill("#auth-password", "123456")
        await page.click("#submit-btn")
        await page.wait_for_timeout(1000)

        error_box = page.locator("#auth-error-box")
        assert await error_box.is_visible(), (
            "LỖI: Hộp thông báo lỗi không hiển thị khi mật khẩu sai!"
        )
        error_text = await error_box.inner_text()
        print(f"  - Thông báo phản hồi từ hệ thống: '{error_text}'", flush=True)
        assert (
            "không chính xác" in error_text.lower() or "khóa" in error_text.lower()
        ), "LỖI: Nội dung lỗi không khớp chuẩn an ninh!"

        shot2 = REPORTS_DIR / "auth_02_weak_password_rejected.png"
        await page.screenshot(path=str(shot2))
        shutil.copy(shot2, ARTIFACT_DIR / "auth_02_weak_password_rejected.png")
        print(
            "  📸 Đã chụp: auth_02_weak_password_rejected.png (Chặn đứng mật khẩu 123456)",
            flush=True,
        )

        # Step 3: Legitimate Login with Hardened Password
        print(
            "[3] Đăng nhập bằng mật khẩu quản trị bảo mật mới DSCons@2026#SecureAdmin...",
            flush=True,
        )
        await page.fill("#auth-email", "admin@dscons.vn")
        await page.fill("#auth-password", "DSCons@2026#SecureAdmin")
        await page.click("#submit-btn")

        # Wait for redirect to /dashboard
        try:
            await page.wait_for_url(f"{BASE_URL}/dashboard", timeout=8000)
        except Exception:
            await page.wait_for_timeout(2500)

        current_url = page.url
        print(f"  - URL hiện tại sau đăng nhập: {current_url}", flush=True)
        assert "/dashboard" in current_url, (
            f"LỖI: Không chuyển hướng thành công vào /dashboard! URL hiện tại: {current_url}"
        )

        await page.wait_for_timeout(1200)
        shot3 = REPORTS_DIR / "auth_03_dashboard_authenticated.png"
        await page.screenshot(path=str(shot3))
        shutil.copy(shot3, ARTIFACT_DIR / "auth_03_dashboard_authenticated.png")
        print(
            "  📸 Đã chụp: auth_03_dashboard_authenticated.png (Đăng nhập thành công)",
            flush=True,
        )

        await browser.close()
        print(
            "\n=======================================================================",
            flush=True,
        )
        print(
            "  KIỂM THỬ TRÌNH DUYỆT THỰC TẾ PLAYWRIGHT HOÀN TẤT THÀNH CÔNG 100%!",
            flush=True,
        )
        print(
            "=======================================================================\n",
            flush=True,
        )


if __name__ == "__main__":
    asyncio.run(run_auth_verification())
