"""Playwright smoke-test harness.

Opens a page and checks, from a JSON config file:
- the title contains expected text
- key texts are present on the page
- a form is present (optional)

On any failure it saves a screenshot so the broken state can be
inspected later. The CLI exits 0 when every check passes and 1
otherwise, so it can gate a deploy or a cron run.

Config format:

    {
      "url": "fixture.html",
      "title_contains": "Fixture",
      "texts": ["Welcome", "Sign up"],
      "require_form": true,
      "screenshot_dir": "screenshots"
    }

A relative url is resolved against the config file directory and
opened as a file:// URL. Absolute http(s) URLs go through the local
relay proxy with certificate errors ignored.
"""

from __future__ import annotations

import argparse
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

from playwright.sync_api import sync_playwright

DEFAULT_PROXY = "http://127.0.0.1:18082"


def load_config(path: str | Path) -> dict:
    config = json.loads(Path(path).read_text(encoding="utf-8"))
    url = config["url"]
    if not url.startswith(("http://", "https://", "file://")):
        url = (Path(path).resolve().parent / url).as_uri()
    config["url"] = url
    config.setdefault("texts", [])
    config.setdefault("require_form", False)
    config.setdefault("screenshot_dir", "screenshots")
    return config


def run_checks(config: dict, proxy: str | None = DEFAULT_PROXY) -> dict:
    """Run the configured checks. Returns a result dict."""
    results: list[dict] = []
    url = config["url"]
    launch_kwargs: dict = {}
    if proxy and url.startswith("http"):
        launch_kwargs["proxy"] = {"server": proxy}

    with sync_playwright() as pw:
        browser = pw.chromium.launch(**launch_kwargs)
        context = browser.new_context(ignore_https_errors=True)
        page = context.new_page()
        page.goto(url)

        expected_title = config.get("title_contains")
        if expected_title:
            title = page.title()
            results.append(
                {
                    "check": "title_contains",
                    "expected": expected_title,
                    "actual": title,
                    "passed": expected_title in title,
                }
            )

        body_text = page.inner_text("body")
        for text in config["texts"]:
            results.append(
                {
                    "check": "text_present",
                    "expected": text,
                    "actual": "found" if text in body_text else "missing",
                    "passed": text in body_text,
                }
            )

        if config["require_form"]:
            form_count = page.locator("form").count()
            results.append(
                {
                    "check": "form_present",
                    "expected": ">= 1 form",
                    "actual": f"{form_count} form(s)",
                    "passed": form_count >= 1,
                }
            )

        passed = all(item["passed"] for item in results)
        screenshot_path = None
        if not passed:
            shot_dir = Path(config["screenshot_dir"])
            shot_dir.mkdir(parents=True, exist_ok=True)
            stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
            screenshot_path = str(shot_dir / f"failure-{stamp}.png")
            page.screenshot(path=screenshot_path)

        browser.close()

    return {"url": url, "passed": passed, "results": results, "screenshot": screenshot_path}


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Playwright smoke-test harness")
    parser.add_argument("--config", required=True, help="Path to config JSON")
    parser.add_argument("--no-proxy", action="store_true", help="Disable proxy")
    args = parser.parse_args(argv)

    config = load_config(args.config)
    result = run_checks(config, proxy=None if args.no_proxy else DEFAULT_PROXY)
    for item in result["results"]:
        mark = "PASS" if item["passed"] else "FAIL"
        print(f"{mark} {item['check']}: expected {item['expected']!r}, got {item['actual']!r}")
    if result["screenshot"]:
        print(f"screenshot saved: {result['screenshot']}")
    print("smoke test passed" if result["passed"] else "smoke test failed")
    return 0 if result["passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
