"""Tests for Linux/POSIX path helpers (remote + Nexus host paths)."""

import pytest

from server.utils.posix_paths import (
    PosixPathError,
    assert_zip_member_safe,
    normalize_remote_abs_path,
    normalize_remote_dest,
    posix_basename,
    posix_dirname,
    posix_join,
    remote_join,
    to_posix,
)


def test_to_posix_converts_backslashes():
    assert to_posix(r"\www\site") == "/www/site"


def test_normalize_remote_abs_path():
    assert normalize_remote_abs_path("/www/wwwroot//site") == "/www/wwwroot/site"
    assert normalize_remote_abs_path("/") == "/"


def test_normalize_rejects_traversal():
    with pytest.raises(PosixPathError):
        normalize_remote_abs_path("/www/../etc/passwd")


def test_normalize_rejects_backslash():
    with pytest.raises(PosixPathError):
        normalize_remote_abs_path(r"\www\site")


def test_posix_join_on_windows_style_input():
    assert posix_join("/www/wwwroot", "m.example.com", "index.php") == (
        "/www/wwwroot/m.example.com/index.php"
    )


def test_posix_dirname_basename():
    assert posix_dirname("/www/wwwroot/app/index.php") == "/www/wwwroot/app"
    assert posix_basename("/www/wwwroot/app/index.php") == "index.php"


def test_remote_join():
    assert remote_join("/www/wwwroot", "index.php") == "/www/wwwroot/index.php"
    assert remote_join("/tmp", "a/b") == "/tmp/a/b"  # segments sanitized via normpath


def test_normalize_remote_dest_default():
    assert normalize_remote_dest(None) == "/tmp/sync"
    assert normalize_remote_dest("/www/wwwroot/site/") == "/www/wwwroot/site"


def test_assert_zip_member_safe():
    base = "/tmp/nexus_upload_abc"
    assert assert_zip_member_safe(base, "foo/bar.txt").startswith(base)
    with pytest.raises(PosixPathError):
        assert_zip_member_safe(base, "../etc/passwd")
