"""Auto-install playwright + chromium on first run."""
from __future__ import annotations

import subprocess
import sys


def _pip_install(pkg: str) -> None:
    print(f"[bootstrap] pip install {pkg} ...", file=sys.stderr)
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", "--quiet", pkg]
    )


def _ensure_playwright_pkg() -> None:
    try:
        import playwright.sync_api  # noqa: F401
        return
    except ImportError:
        pass
    _pip_install("playwright")


def ensure_chromium() -> None:
    """Install the chromium browser via `playwright install`."""
    print("[bootstrap] playwright install chromium ...", file=sys.stderr)
    subprocess.check_call(
        [sys.executable, "-m", "playwright", "install", "chromium"]
    )


def ensure_runtime() -> None:
    """Make sure the playwright pip package is importable."""
    _ensure_playwright_pkg()
