import socket
from functools import lru_cache
from pathlib import Path

import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--no-gpfs",
        action="store_true",
        default=False,
        help="Skips tests marked as requiring GPFS access",
    )

    parser.addoption(
        "--no-mdc",
        action="store_true",
        default=True,
        help="Skips tests marked as requiring myMDC access",
    )


def pytest_configure(config):
    config.addinivalue_line(
        "markers",
        "requires_gpfs(): marks skips for tests that require GPFS access",
    )

    config.addinivalue_line(
        "markers",
        "requires_caldb(): marks skips for tests that require calDB access",
    )

    config.addinivalue_line(
        "markers",
        "requires_mdc(): marks skips for tests that require calDB access",
    )


@lru_cache()
def server_reachable(server: str = "max-exfl017"):
    reachable = True

    try:
        socket.getaddrinfo(server, port=80)
    except socket.gaierror:
        reachable = False

    return reachable


def pytest_runtest_setup(item):
    if list(item.iter_markers(name="requires_gpfs")) and (
        not Path("/gpfs").is_dir() or item.config.getoption("--no-gpfs")
    ):
        pytest.skip("gpfs not available")

    if list(item.iter_markers(name="requires_caldb")) and not server_reachable():
        pytest.skip("caldb not available")

    if (
        list(item.iter_markers(name="requires_mdc")) and
        item.config.getoption("--no-mdc")
    ):
        pytest.skip("myMDC not available")