import socket
import sys

import pytest
from clarabot_nano_common.utility.path.validate import denormalize_absolute_path, ValidationError

_LOCALHOST_NAME = socket.gethostname()

DENORMALIZE_ABSOLUTE_PATHS_POSIX_ = [
    "/x/y",
    "/",
    "/x/",
]
DENORMALIZE_ABSOLUTE_PATHS_ROOT_NT_ = [
    "c:/",
    "//?/c:/",
    "//LOCALHOST/c$",
    "//LOCALHOST/c$/",
    "//127.0.0.1/C$/",
    "//::1/c$/",
    f"//{_LOCALHOST_NAME}/C$/",
    "//?/c:/",
    "//?/UNC/LOCALHOST/c$/",
]
DENORMALIZE_ABSOLUTE_PATHS_NT_ = [
    r"c:\x/y",
    r"\\?\c:\x/y",
    r"\\LOCALHOST\c$\x/y",
    r"\\127.0.0.1\C$\x/y/",
    r"\\::1\c$\x/y/",
    rf"\\{_LOCALHOST_NAME}\C$\x/y",
    r"\\?\c:\x/y/",
    r"\\?\UNC\LOCALHOST\c$\x/y",
]
DENORMALIZE_INVALID_PATHS_ALL_ = [
    "//",
    r"c:",
    r"xy",
    r"\x/y",
    r"c:x/y",
    r"\\?\c\x/y",
    r"\\?\UNC\BROKE",
    r"\\BROKE",
    "//LOCALHOST/xy",
    "//?/UNC/LOCALHOST/xy",
    "//YXY/c$",
    "//?/UNC/YXY/c$",
    r"c:\x\y|",
]


def test_utility_path_validate_denormalize_absolute_path_universal():
    for p in DENORMALIZE_INVALID_PATHS_ALL_:
        with pytest.raises(ValidationError):
            denormalize_absolute_path(p)


@pytest.mark.skipif(sys.platform.startswith("win"), reason="for posix only")
def test_utility_path_validate_denormalize_absolute_path_posix():
    for p in DENORMALIZE_ABSOLUTE_PATHS_ROOT_NT_ + DENORMALIZE_ABSOLUTE_PATHS_NT_:
        with pytest.raises(ValidationError):
            denormalize_absolute_path(p)
    for p in DENORMALIZE_ABSOLUTE_PATHS_POSIX_:
        r = p.rstrip("/") if len(p) > 1 else p
        assert denormalize_absolute_path(p) == r


@pytest.mark.skipif(not sys.platform.startswith("win"), reason="for windows only")
def test_utility_path_validate_denormalize_absolute_path_nt():
    for p in DENORMALIZE_ABSOLUTE_PATHS_ROOT_NT_:
        assert denormalize_absolute_path(p) == "C:\\"
    for p in DENORMALIZE_ABSOLUTE_PATHS_NT_:
        assert denormalize_absolute_path(p) == "C:\\x\\y"
    for p in DENORMALIZE_ABSOLUTE_PATHS_POSIX_:
        with pytest.raises(ValidationError):
            denormalize_absolute_path(p)
