# polisplexity/core/urlbuild.py
from django.conf import settings

def public_base(request=None) -> str:
    """
    1) settings.PUBLIC_BASE_URL (recommended in prod)
    2) request scheme/host (proxy aware)
    3) http://localhost:8000 fallback
    """
    base = getattr(settings, "PUBLIC_BASE_URL", "").rstrip("/")
    if base:
        return base
    if request is not None:
        proto = (request.META.get("HTTP_X_FORWARDED_PROTO")
                 or ("https" if request.is_secure() else "http"))
        host = request.get_host()
        return f"{proto.split(',')[0].strip()}://{host}"
    return "http://localhost:8000"

def public_url(path_or_abs: str, request=None) -> str:
    """Join public base to a path; pass through absolute URLs untouched."""
    if not path_or_abs:
        return path_or_abs
    if "://" in path_or_abs:
        return path_or_abs
    if not path_or_abs.startswith("/"):
        path_or_abs = "/" + path_or_abs
    return public_base(request) + path_or_abs
