"""E2E test configuration — auto-skip when no K8s cluster is available."""

from __future__ import annotations

import subprocess

import pytest


def _cluster_available() -> bool:
    """Check if a K8s cluster is reachable."""
    try:
        result = subprocess.run(
            ["kubectl", "cluster-info"],
            capture_output=True,
            timeout=5,
        )
        return result.returncode == 0
    except Exception:
        return False


def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
    """Skip E2E tests when no K8s cluster is available.

    E2E tests always use a real cluster (make_real_factory → K8sClient.from_context).
    They auto-skip gracefully if kubectl can't reach a cluster.
    """
    # Collect only e2e items
    e2e_items = [
        item for item in items if "/e2e/" in str(item.fspath) or "\\e2e\\" in str(item.fspath)
    ]
    if not e2e_items:
        return

    backend = config.getoption("--backend", default="fake")
    if backend != "real" or not _cluster_available():
        skip_marker = pytest.mark.skip(reason="No K8s cluster available (or --backend fake)")
        for item in e2e_items:
            item.add_marker(skip_marker)
        return

    # E2E tests involve real K8s operations (pod scheduling, rolling updates,
    # image pulls) that genuinely need more than the default 45s timeout.
    timeout_marker = pytest.mark.timeout(300)
    for item in e2e_items:
        item.add_marker(timeout_marker)
