"""Skip live glue checks when the VictoriaMetrics endpoint is unavailable."""

from __future__ import annotations

import os
import socket
from urllib.parse import urlparse

import pytest


def _endpoint_available() -> bool:
    """Return whether the configured VictoriaMetrics host resolves locally."""
    vm_url = os.environ.get("VM_URL", "http://victoria-metrics-single-server:8428").rstrip("/")
    parsed = urlparse(vm_url)
    host = parsed.hostname
    port = parsed.port or (443 if parsed.scheme == "https" else 80)
    if not host:
        return False
    try:
        socket.getaddrinfo(host, port)
    except socket.gaierror:
        return False
    return True


def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
    """Mark glue tests skipped when the VictoriaMetrics host cannot resolve."""
    del config
    if _endpoint_available():
        return
    skip_marker = pytest.mark.skip(reason="VictoriaMetrics endpoint is not reachable in this workspace")
    for item in items:
        item.add_marker(skip_marker)
