"""Deployment configuration for the LaksyaShrimp Flask application.

The Flask process still listens on an internal port (normally 5899), but all
public/customer-facing links and QR codes use the CIBA reverse-proxy URL.
"""

import os

# Public URL users should see.  Override with an environment variable only if
# the application is deployed under a different public path.
PUBLIC_BASE_URL = os.getenv(
    "PUBLIC_BASE_URL",
    "https://ciba.res.in/laksyashrimp",
).rstrip("/")

# Public path where the reverse proxy mounts this Flask application.
PUBLIC_PATH = os.getenv("PUBLIC_PATH", "/laksyashrimp").rstrip("/") or "/"

# Internal Flask listener; this is NOT used in QR codes.
FLASK_HOST = os.getenv("FLASK_HOST", "0.0.0.0")
FLASK_PORT = int(os.getenv("FLASK_PORT", os.getenv("FLASK_RUN_PORT", "5899")))


def public_url(path=""):
    """Return an absolute public URL for an application-relative path."""
    path = str(path or "")
    if path.startswith("http://") or path.startswith("https://"):
        return path
    if not path.startswith("/"):
        path = "/" + path
    # If callers pass the public prefix explicitly, do not duplicate it.
    if PUBLIC_PATH != "/" and (path == PUBLIC_PATH or path.startswith(PUBLIC_PATH + "/")):
        public_path = path
    else:
        public_path = f"{PUBLIC_PATH}{path}" if PUBLIC_PATH != "/" else path
    return f"{PUBLIC_BASE_URL}{public_path[len(PUBLIC_PATH):] if PUBLIC_PATH != '/' and public_path.startswith(PUBLIC_PATH) else public_path}"
