"""
Utility to ensure upload directories exist with correct permissions
before saving files (KYC, POD, etc.).
"""
import os
from pathlib import Path

from django.conf import settings


def ensure_upload_dir(relative_path: str) -> Path:
    """
    Ensure the upload directory exists. Create it (and parent dirs) with
    permissions if not available. Returns the full path.

    relative_path: path relative to MEDIA_ROOT (e.g. 'kyc/2026/03/19')

    On PermissionError: media dir may not be writable by the web process
    (often www-data). Fix on the server, e.g.:

        sudo mkdir -p /var/www/html/truck-me/media
        sudo chown -R www-data:www-data /var/www/html/truck-me/media
        sudo chmod -R u+rwX,g+rwX /var/www/html/truck-me/media
    """
    media_root = Path(settings.MEDIA_ROOT)
    full_path = (media_root / relative_path).resolve()

    try:
        if not full_path.exists():
            full_path.mkdir(parents=True, exist_ok=True)
            try:
                os.chmod(full_path, 0o775)
            except OSError:
                pass
        # Fail fast with a clear error if the process cannot write here.
        probe = full_path / '.write_probe'
        try:
            probe.write_text('', encoding='utf-8')
            probe.unlink(missing_ok=True)
        except PermissionError as exc:
            raise PermissionError(
                f'Cannot write to media directory {full_path}. '
                f'Ensure the web server user owns MEDIA_ROOT '
                f'({media_root}) and can create files there. '
                f'Example: sudo chown -R www-data:www-data {media_root} '
                f'&& sudo chmod -R u+rwX,g+rwX {media_root}'
            ) from exc
    except PermissionError:
        raise

    return full_path
