#!/usr/bin/env python3
"""
Playwright Test Script for Genesis System
Proves browser automation is working on WSL2.
Navigates to a website, takes a screenshot, extracts text.

Usage:
    LD_LIBRARY_PATH=/mnt/e/genesis-system/.venvs/playwright-libs/usr/lib/x86_64-linux-gnu python3 scripts/playwright_test.py
"""

import os
import sys
from pathlib import Path
from datetime import datetime

# Set LD_LIBRARY_PATH if not already set
LIBS_PATH = "/mnt/e/genesis-system/.venvs/playwright-libs/usr/lib/x86_64-linux-gnu"
if LIBS_PATH not in os.environ.get("LD_LIBRARY_PATH", ""):
    os.environ["LD_LIBRARY_PATH"] = f"{LIBS_PATH}:{os.environ.get('LD_LIBRARY_PATH', '')}"

from playwright.sync_api import sync_playwright

OUTPUT_DIR = Path("/mnt/e/genesis-system/data")
SCREENSHOT_PATH = OUTPUT_DIR / "playwright_test.png"


def run_test():
    """Full Playwright test: navigate, screenshot, extract text."""
    results = {
        "timestamp": datetime.now().isoformat(),
        "tests": [],
        "overall": "UNKNOWN",
    }

    with sync_playwright() as p:
        # Test 1: Launch browser
        print("[TEST 1] Launching Chromium (headless, no-sandbox)...")
        try:
            browser = p.chromium.launch(
                headless=True,
                args=["--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage"],
            )
            results["tests"].append({"name": "browser_launch", "status": "PASS"})
            print("  PASS - Browser launched successfully")
        except Exception as e:
            results["tests"].append({"name": "browser_launch", "status": "FAIL", "error": str(e)})
            print(f"  FAIL - {e}")
            results["overall"] = "FAIL"
            return results

        page = browser.new_page(viewport={"width": 1920, "height": 1080})

        # Test 2: Navigate to website
        print("[TEST 2] Navigating to https://example.com...")
        try:
            page.goto("https://example.com", wait_until="networkidle")
            title = page.title()
            assert "Example" in title, f"Unexpected title: {title}"
            results["tests"].append({"name": "navigation", "status": "PASS", "title": title})
            print(f"  PASS - Title: {title}")
        except Exception as e:
            results["tests"].append({"name": "navigation", "status": "FAIL", "error": str(e)})
            print(f"  FAIL - {e}")

        # Test 3: Take screenshot
        print(f"[TEST 3] Taking screenshot -> {SCREENSHOT_PATH}...")
        try:
            page.screenshot(path=str(SCREENSHOT_PATH), full_page=True)
            assert SCREENSHOT_PATH.exists(), "Screenshot file not created"
            size_kb = SCREENSHOT_PATH.stat().st_size / 1024
            results["tests"].append({"name": "screenshot", "status": "PASS", "size_kb": round(size_kb, 1)})
            print(f"  PASS - Screenshot saved ({size_kb:.1f} KB)")
        except Exception as e:
            results["tests"].append({"name": "screenshot", "status": "FAIL", "error": str(e)})
            print(f"  FAIL - {e}")

        # Test 4: Extract text
        print("[TEST 4] Extracting page text...")
        try:
            text = page.inner_text("body")
            assert len(text) > 0, "No text extracted"
            assert "Example Domain" in text, f"Expected text not found in: {text[:100]}"
            results["tests"].append({"name": "text_extraction", "status": "PASS", "text_length": len(text)})
            print(f"  PASS - Extracted {len(text)} characters")
            print(f"  Text: {text.strip()[:200]}")
        except Exception as e:
            results["tests"].append({"name": "text_extraction", "status": "FAIL", "error": str(e)})
            print(f"  FAIL - {e}")

        # Test 5: Execute JavaScript
        print("[TEST 5] Executing JavaScript...")
        try:
            js_result = page.evaluate("() => ({ url: window.location.href, userAgent: navigator.userAgent })")
            assert "example.com" in js_result["url"], f"Unexpected URL: {js_result['url']}"
            results["tests"].append({"name": "javascript_execution", "status": "PASS", "url": js_result["url"]})
            print(f"  PASS - URL: {js_result['url']}")
            print(f"  User-Agent: {js_result['userAgent'][:80]}...")
        except Exception as e:
            results["tests"].append({"name": "javascript_execution", "status": "FAIL", "error": str(e)})
            print(f"  FAIL - {e}")

        # Test 6: Navigate to a more complex page
        print("[TEST 6] Navigating to httpbin.org/html...")
        try:
            page.goto("https://httpbin.org/html", wait_until="networkidle", timeout=15000)
            title = page.title()
            body_text = page.inner_text("body")
            results["tests"].append({
                "name": "complex_navigation",
                "status": "PASS",
                "title": title,
                "text_length": len(body_text),
            })
            print(f"  PASS - Title: {title}, Text length: {len(body_text)}")
        except Exception as e:
            results["tests"].append({"name": "complex_navigation", "status": "FAIL", "error": str(e)})
            print(f"  FAIL - {e}")

        # Cleanup
        browser.close()

    # Summary
    passed = sum(1 for t in results["tests"] if t["status"] == "PASS")
    failed = sum(1 for t in results["tests"] if t["status"] == "FAIL")
    total = len(results["tests"])
    results["overall"] = "PASS" if failed == 0 else "FAIL"
    results["summary"] = f"{passed}/{total} tests passed"

    print(f"\n{'='*60}")
    print(f"RESULT: {results['overall']} - {results['summary']}")
    print(f"Screenshot: {SCREENSHOT_PATH}")
    print(f"{'='*60}")

    return results


if __name__ == "__main__":
    results = run_test()
    sys.exit(0 if results["overall"] == "PASS" else 1)
