"""Reusable filesystem-safety boundary for client-supplied offer file names.

Two independent guarantees, both required (validation is never a substitute
for containment):

1. Filename validation -- the client value must denote exactly one path
   component. Document names keep spaces and Unicode; offer-image names must
   match the server-generated grammar. Anything that could denote a parent
   ref, an absolute path, a drive-qualified path, a nested path or a
   directory separator (POSIX or Windows) is rejected.
2. Containment -- after resolving the child beneath its intended base
   directory, the resolved real path must still lie inside that base. This
   is checked with pathlib resolution so it holds on both Windows
   development and Linux/cPanel production, not by string prefix comparison.

The offer-image grammar lives here as the single source of truth; the public
media blueprint imports it so the two layers cannot drift apart.
"""
from __future__ import annotations

import ntpath
import os
import posixpath
from pathlib import Path

from modules.core.offer_media import OFFER_IMAGE_RE

class UnsafeFilename(ValueError):
    """A client-supplied filename failed validation or containment.

    Carries only a generic, path-free reason so callers can return a 4xx
    without leaking resolved filesystem locations to the client.
    """


def _reject_if_not_single_component(name: str) -> None:
    """Reject anything that is not exactly one plain path component, on either
    OS. Separators, drive prefixes, nested paths, '.'/'..', empty values and
    control characters (incl. NUL) are all rejected."""
    if not isinstance(name, str):
        raise UnsafeFilename("filename must be text")

    candidate = name.strip()
    if not candidate or candidate in (".", ".."):
        raise UnsafeFilename("empty or special filename")

    if "/" in candidate or "\\" in candidate:
        raise UnsafeFilename("filename must not contain path separators")

    if ":" in candidate:  # Windows drive / alternate data stream
        raise UnsafeFilename("filename must not contain a drive or stream")

    # basename under BOTH path flavours must return the value unchanged; this
    # catches OS-specific separators and drive prefixes regardless of the
    # platform the code runs on.
    if os.path.basename(candidate) != candidate:
        raise UnsafeFilename("filename must be a single path component")
    if posixpath.basename(candidate) != candidate:
        raise UnsafeFilename("filename must be a single path component")
    if ntpath.basename(candidate) != candidate:
        raise UnsafeFilename("filename must be a single path component")

    if any(ord(ch) < 32 for ch in candidate):
        raise UnsafeFilename("filename contains control characters")


def validate_document_filename(name) -> str:
    """Validate a user-visible document filename, preserving spaces and
    Unicode. Returns the stripped filename or raises UnsafeFilename."""
    _reject_if_not_single_component(name)
    return name.strip()


def validate_offer_image_filename(offer_id, name) -> str:
    """Validate a server-generated offer-image filename and confirm the offer
    id embedded in it matches the route's offer id. Returns the filename or
    raises UnsafeFilename."""
    if not isinstance(name, str):
        raise UnsafeFilename("filename must be text")
    match = OFFER_IMAGE_RE.match(name.strip())
    if not match or int(match.group("id")) != int(offer_id):
        raise UnsafeFilename("not a valid offer image filename")
    return name.strip()


def safe_child_path(base_dir, name: str) -> Path:
    """Resolve `name` beneath `base_dir` and confirm the resolved real path
    stays strictly inside `base_dir`. `name` must already be a validated
    single component. Raises UnsafeFilename on escape."""
    _reject_if_not_single_component(name)
    base = Path(base_dir).resolve()
    candidate = (base / name.strip()).resolve()
    if candidate == base or not candidate.is_relative_to(base):
        raise UnsafeFilename("resolved path escapes the base directory")
    return candidate
