import hashlib
import re
from pathlib import Path

# Windows-friendly path component sanitizer with length control
_INVALID_CHARS = re.compile(r"[^A-Za-z0-9._\-+]+")


def safe_component(name: str, max_len: int = 64) -> str:
    """
    Return a filesystem-safe, short component for use in paths across OSes.
    - Replaces path separators with '__'
    - Removes characters outside [A-Za-z0-9._-+]
    - Truncates to max_len and appends a short hash to preserve uniqueness
    """
    if name is None:
        return "none"
    # Normalize separators
    s = str(name).replace("\\", "/").replace("/", "__")
    # Collapse invalid chars to '_'
    s = _INVALID_CHARS.sub("_", s)
    # Strip leading/trailing dots/spaces which can be problematic on Windows
    s = s.strip(" .") or "_"
    if len(s) <= max_len:
        return s
    # Append a short stable hash to keep it unique
    h = hashlib.sha1(s.encode("utf-8")).hexdigest()[:8]
    return f"{s[:max_len-9]}_{h}"


def build_eval_log_dir(base: Path, run_id: str, model_name: str, instance_id: str) -> Path:
    """
    Construct the log directory path used by evaluation harness with safe components.
    """
    return base / safe_component(run_id) / safe_component(model_name) / safe_component(instance_id)
