"""Tests for naming module."""

import re

from smriti.naming import (
    build_session_name,
    get_dir_pattern,
    get_hostname,
    get_path_hash,
    sanitize,
)


def test_sanitize_strips_special_chars():
    assert sanitize("hello world!@#") == "helloworld"


def test_sanitize_preserves_hyphens_underscores():
    assert sanitize("my-project_v2") == "my-project_v2"


def test_sanitize_path_traversal():
    assert sanitize("../../etc/passwd") == "etcpasswd"


def test_sanitize_empty():
    assert sanitize("") == ""


def test_sanitize_unicode():
    assert sanitize("proj-naïve") == "proj-nave"


def test_build_session_name_format():
    name = build_session_name("dev")
    # Format: hostname-dirname-hash-tag-YYYYMMDD-HHMMSS
    parts = name.split("-")
    assert len(parts) >= 5
    assert "dev" in name


def test_build_session_name_default_tag():
    name = build_session_name()
    assert "session" in name


def test_build_session_name_timestamp_format():
    name = build_session_name("test")
    # Timestamp should be YYYYMMDD-HHMMSS at the end
    match = re.search(r"\d{8}-\d{6}$", name)
    assert match is not None


def test_build_session_name_contains_path_hash():
    name = build_session_name("dev")
    path_hash = get_path_hash()
    assert path_hash in name


def test_get_path_hash_is_stable():
    """Same directory should produce same hash."""
    h1 = get_path_hash()
    h2 = get_path_hash()
    assert h1 == h2
    assert len(h1) == 4
    assert re.match(r"^[0-9a-f]+$", h1)


def test_get_path_hash_different_dirs(tmp_path, monkeypatch):
    """Different directories should produce different hashes."""
    original_hash = get_path_hash()

    monkeypatch.chdir(tmp_path)
    tmp_hash = get_path_hash()

    assert original_hash != tmp_hash


def test_get_dir_pattern_basic():
    pattern = get_dir_pattern()
    hostname = get_hostname()
    assert pattern.startswith(hostname + "-")
    assert pattern.endswith("-")
    # Should include the path hash
    assert get_path_hash() in pattern


def test_get_dir_pattern_with_tag():
    pattern = get_dir_pattern(tag_filter="cc")
    assert pattern.endswith("cc-")


def test_get_hostname_is_sanitized():
    hostname = get_hostname()
    assert re.match(r"^[a-zA-Z0-9_-]+$", hostname)
