"""Build absolute URLs for uploaded files (media) for mobile clients."""
from django.conf import settings


def build_absolute_media_url(request, relative_url: str) -> str:
    """
    Build an absolute URL for a FileField's `.url` (typically starting with `/media/...`).

    If `PUBLIC_BASE_URL` is set in settings (e.g. `https://api.example.com`), it is used as
    the origin so URLs are correct behind nginx/reverse proxy (avoids `http://127.0.0.1:8000`
    or internal hostnames). Otherwise falls back to `request.build_absolute_uri`.
    """
    if not relative_url:
        return relative_url
    base = (getattr(settings, 'PUBLIC_BASE_URL', None) or '').strip().rstrip('/')
    if base:
        path = relative_url if str(relative_url).startswith('/') else f'/{relative_url}'
        return f'{base}{path}'
    if request is not None:
        return request.build_absolute_uri(relative_url)
    return str(relative_url)
