"""Session naming and sanitization.

Format: <hostname>-<dirname>-<pathhash>-<tag>-<YYYYMMDD-HHMMSS>
Examples:
    gpu01-vajra-a3f1-session-20260212-143022
    gpu01-niti-b7c2-dev-20260212-150000
    gpu01-maya-d4e5-cc-20260212-160000

The 4-char path hash disambiguates directories with the same basename
(e.g., ~/projects/vajra vs ~/work/vajra).
"""

import hashlib
import os
import re
import socket
from datetime import datetime

from .config import MAX_DIRNAME_LEN

# Length of the path hash in the session name
PATH_HASH_LEN = 4


def sanitize(value: str) -> str:
    """Remove all chars except alphanumeric, hyphens, underscores."""
    return re.sub(r"[^a-zA-Z0-9_-]", "", value)


def get_hostname() -> str:
    """Short hostname, sanitized."""
    return sanitize(socket.gethostname().split(".")[0])


def get_dirname() -> str:
    """Current directory basename, sanitized and truncated."""
    raw = os.path.basename(os.getcwd())
    cleaned = sanitize(raw.replace(" ", "_").replace(".", "_"))
    return cleaned[:MAX_DIRNAME_LEN]


def get_path_hash() -> str:
    """Short hash of the full cwd path for disambiguation."""
    full_path = os.getcwd()
    return hashlib.sha1(full_path.encode()).hexdigest()[:PATH_HASH_LEN]


def get_timestamp() -> str:
    """YYYYMMDD-HHMMSS format."""
    return datetime.now().strftime("%Y%m%d-%H%M%S")


def build_session_name(tag: str = "session") -> str:
    """Build full session name."""
    return (
        f"{get_hostname()}-{get_dirname()}-{get_path_hash()}" f"-{sanitize(tag)}-{get_timestamp()}"
    )


def get_dir_pattern(tag_filter: str | None = None) -> str:
    """Pattern to match sessions for current host + dir + path hash.

    Optionally filtered by tag.
    """
    base = f"{get_hostname()}-{get_dirname()}-{get_path_hash()}-"
    if tag_filter:
        base += f"{sanitize(tag_filter)}-"
    return base
