"""Playwright CLI browser automation installation."""

from __future__ import annotations

import subprocess
from pathlib import Path
from typing import Any

from installer.platform_utils import command_exists
from installer.steps.deps_utils import _run_bash_with_retry


def _get_playwright_cache_dirs() -> list[Path]:
    """Get possible Playwright cache directories for the current platform."""
    import platform

    dirs = []
    if platform.system() == "Darwin":
        dirs.append(Path.home() / "Library" / "Caches" / "ms-playwright")
    dirs.append(Path.home() / ".cache" / "ms-playwright")
    return dirs


def _is_playwright_cli_ready() -> bool:
    """Check if playwright-cli is installed and Chromium is available."""
    if not command_exists("playwright-cli"):
        return False

    for cache_dir in _get_playwright_cache_dirs():
        if not cache_dir.exists():
            continue

        for chromium_dir in cache_dir.glob("chromium-*"):
            if (chromium_dir / "INSTALLATION_COMPLETE").exists():
                return True

        for chromium_dir in cache_dir.glob("chromium_headless_shell-*"):
            if (chromium_dir / "INSTALLATION_COMPLETE").exists():
                return True

    return False


def _install_playwright_system_deps(ui: Any = None) -> bool:
    """Install OS-level system dependencies required by Playwright browsers.

    Runs 'npx playwright install-deps' which installs system libraries
    (libglib, libatk, etc.) needed by Chromium. Required on Linux/devcontainers,
    no-op on macOS.
    """
    try:
        if ui:
            with ui.spinner("Installing browser system dependencies..."):
                result = subprocess.run(
                    ["npx", "-y", "playwright", "install-deps"],
                    capture_output=True,
                    text=True,
                    timeout=300,
                )
        else:
            result = subprocess.run(
                ["npx", "-y", "playwright", "install-deps"],
                capture_output=True,
                text=True,
                timeout=300,
            )
        return result.returncode == 0
    except Exception:
        return False


def install_playwright_cli(ui: Any = None) -> bool:
    """Install playwright-cli for headless browser automation.

    Shows verbose output during installation with download progress.
    Skips verbose output if already installed.
    """
    if _is_playwright_cli_ready():
        return True

    if not _run_bash_with_retry("npm install -g @playwright/cli@latest"):
        return False

    if _is_playwright_cli_ready():
        _install_playwright_system_deps(ui)
        return True

    try:
        spinner_label = "Downloading Chromium browser..."
        if ui:
            with ui.spinner(spinner_label):
                result = subprocess.run(
                    ["playwright-cli", "install"],
                    capture_output=True,
                    text=True,
                    timeout=300,
                )
        else:
            result = subprocess.run(
                ["playwright-cli", "install"],
                capture_output=True,
                text=True,
                timeout=300,
            )
        if result.returncode != 0:
            return False
    except Exception:
        return False

    _install_playwright_system_deps(ui)
    return True
