"""Map extracted archive member paths to R2 object keys."""
from __future__ import annotations

import os


def flatten_archive_relative_path(relative: str) -> str:
    """Turn ``folder/sub/file.png`` into ``folder-sub-file.png`` (single key segment)."""
    parts = relative.replace("\\", "/").strip("/").split("/")
    if not parts:
        return "file"
    if len(parts) == 1:
        return parts[0]
    return "-".join(parts)


def object_key_for_extracted_file(*, prefix: str, relative: str, archive_path_mode: str) -> str:
    rel = relative.replace("\\", "/").lstrip("/")
    if archive_path_mode == "flatten":
        rel = flatten_archive_relative_path(rel)
    base = prefix.strip().replace("\\", "/").strip("/")
    return f"{base}/{rel}" if base else rel


def connection_path_prefix(config: dict | None) -> str:
    """Normalize the optional connector ``path_prefix`` used by Cloud list/presign."""
    return str((config or {}).get("path_prefix") or "").replace("\\", "/").strip("/")


def apply_connection_prefix(prefix: str, key: str) -> str:
    """Write keys under the same prefix Cloud ``list_objects`` reads."""
    normalized_key = (key or "").replace("\\", "/").lstrip("/")
    normalized_prefix = (prefix or "").replace("\\", "/").strip("/")
    if not normalized_prefix:
        return normalized_key
    if not normalized_key:
        return normalized_prefix
    if normalized_key == normalized_prefix or normalized_key.startswith(f"{normalized_prefix}/"):
        return normalized_key
    return f"{normalized_prefix}/{normalized_key}"


def staging_abs_path(root: str, relative: str) -> str:
    return os.path.join(os.path.normpath(root), (relative or "").replace("/", os.sep))


def staging_file_is_visible(root: str, relative: str) -> bool:
    """True only when this process can read the staged upload from local disk."""
    path = staging_abs_path(root, relative)
    return bool(relative) and os.path.isfile(path)
