"""Path and naming helpers for NPZ snapshot storage."""

from __future__ import annotations

import re


def radar_key_from_config(
    model_name: str,
    serial: str,
    sweep_start_hz: float,
    sweep_stop_hz: float,
    sweep_points: int,
    ifbw_hz: float,
    power_dbm: float,
) -> str:
    """Build deterministic key for calibration/reference set lookup."""
    serial_part = serial or "no_serial"
    start_token = _format_float_for_key(sweep_start_hz)
    stop_token = _format_float_for_key(sweep_stop_hz)
    ifbw_token = _format_float_for_key(ifbw_hz)
    power_token = _format_float_for_key(power_dbm)
    return (
        f"{model_name}_{serial_part}"
        f"_st{start_token}_sp{stop_token}"
        f"_p{sweep_points}_if{ifbw_token}_pw{power_token}"
    )


def collection_dir_name(index: int, collection_id: int, monotonic_ns: int) -> str:
    """Build canonical collection directory name for snapshot stages."""
    return f"{index:04d}_id{int(collection_id)}_ns{int(monotonic_ns)}"


def sanitize_path_component(name: str) -> str:
    """Convert arbitrary string into filesystem-safe component."""
    cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", name.strip())
    cleaned = cleaned.strip("._")
    return cleaned or "snapshot"


def format_float_for_key(value: float) -> str:
    """Format float compactly for deterministic key serialization."""
    integer = int(round(value))
    if abs(value - float(integer)) < 1e-6:
        return str(integer)
    return f"{value:.6f}".rstrip("0").rstrip(".")


def _format_float_for_key(value: float) -> str:
    """Private alias preserved for internal compatibility."""
    return format_float_for_key(value)
