from __future__ import annotations

"""Playwright Browser Automation Verification for 7 Security Hardening Fixes."""

import asyncio
import shutil
import sys
from pathlib import Path

from playwright.async_api import async_playwright

if sys.platform == "win32":
    sys.stdout.reconfigure(encoding="utf-8")

BASE_URL = "http://127.0.0.1:8000"
ARTIFACTS_DIR = Path(
    "C:/Users/Admin/.gemini/antigravity/brain/eeb7e766-f7b2-43fd-92ef-52b79739803b"
)
SCREENSHOT_DIR = Path("reports/screenshots")


async def main():
    SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
    ARTIFACTS_DIR.mkdir(parents=True, exist_ok=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()

        print("\n--- 1. Testing Unauthenticated Access to /docs ---")
        docs_resp = await page.goto(f"{BASE_URL}/docs")
        print(f"Status for unauthenticated /docs: {docs_resp.status}")
        assert docs_resp.status == 401, (
            f"Expected 401 for unauthenticated /docs, got {docs_resp.status}"
        )

        # Capture screenshot of 401 response
        shot1 = SCREENSHOT_DIR / "sec_01_docs_unauthorized.png"
        await page.screenshot(path=str(shot1))
        shutil.copy(shot1, ARTIFACTS_DIR / shot1.name)
        print(f"Captured: {shot1.name}")

        print("\n--- 2. Inspecting Security Headers (CSP & HSTS) ---")
        headers = docs_resp.headers
        csp = headers.get("content-security-policy", "")
        hsts = headers.get("strict-transport-security", "")
        print(f"CSP: {csp[:80]}...")
        print(f"HSTS: {hsts}")
        assert "default-src 'self'" in csp, "Missing default-src 'self' in CSP"
        assert "max-age=31536000" in hsts, "Missing max-age=31536000 in HSTS"

        print("\n--- 3. Testing Login Page & Auto-Register Block ---")
        await page.goto(f"{BASE_URL}/login")
        await page.wait_for_selector("#email-login-form")

        # Attempt login with random unknown email
        await page.fill("#auth-email", "unknown_hacker_user@evil.com")
        await page.fill("#auth-password", "HackerPassword@123456")
        await page.click("#submit-btn")

        await page.wait_for_selector("#auth-error-box:not(.hidden)", timeout=5000)
        err_text = await page.inner_text("#auth-error-box")
        print(f"Error message for unknown account: {err_text}")

        shot2 = SCREENSHOT_DIR / "sec_02_unknown_email_rejected.png"
        await page.screenshot(path=str(shot2))
        shutil.copy(shot2, ARTIFACTS_DIR / shot2.name)
        print(f"Captured: {shot2.name}")

        print("\n--- 4. Logging in as Superadmin with Secure Admin Password ---")
        await page.fill("#auth-email", "admin@dscons.vn")
        await page.fill("#auth-password", "DSCons@2026#SecureAdmin")
        await page.click("#submit-btn")

        # Wait for redirection to /dashboard
        await page.wait_for_url(f"{BASE_URL}/dashboard", timeout=8000)
        print(f"Navigated to: {page.url}")

        # Check cookies
        cookies = await context.cookies()
        jwt_cookie = next((c for c in cookies if c["name"] == "dscons_jwt_token"), None)
        assert jwt_cookie is not None, "Missing dscons_jwt_token HttpOnly cookie"
        print(
            f"Found HttpOnly cookie: {jwt_cookie['name']} (httpOnly={jwt_cookie['httpOnly']})"
        )

        shot3 = SCREENSHOT_DIR / "sec_03_dashboard_authenticated.png"
        await page.screenshot(path=str(shot3))
        shutil.copy(shot3, ARTIFACTS_DIR / shot3.name)
        print(f"Captured: {shot3.name}")

        print("\n--- 5. Accessing Protected /docs with Authenticated Session ---")
        docs_auth_resp = await page.goto(f"{BASE_URL}/docs")
        print(f"Status for authenticated /docs: {docs_auth_resp.status}")
        assert docs_auth_resp.status == 200, (
            f"Expected 200 for authenticated /docs, got {docs_auth_resp.status}"
        )

        # Wait for Swagger UI container
        await page.wait_for_selector("#swagger-ui", timeout=8000)
        shot4 = SCREENSHOT_DIR / "sec_04_swagger_docs_authenticated.png"
        await page.screenshot(path=str(shot4))
        shutil.copy(shot4, ARTIFACTS_DIR / shot4.name)
        print(f"Captured: {shot4.name}")

        await browser.close()
        print("\n[SUCCESS] ALL 7 SECURITY FIXES VERIFIED IN BROWSER AUTOMATION!")


if __name__ == "__main__":
    asyncio.run(main())
