from __future__ import annotations

import os
from urllib.parse import quote

from config import config


def _get_app_url(app_name: str) -> str:
    env_key = f"APP_URL_{app_name.upper()}"
    env_val = os.getenv(env_key)
    if env_val:
        return env_val.rstrip("/")
    return config()["app_urls"][app_name].rstrip("/")


def app_url(app_name: str, path: str = "/") -> str:
    base = _get_app_url(app_name)
    if not path.startswith("/"):
        path = "/" + path
    return base + path


def coop_url(path: str = "/") -> str:
    return app_url("coop", path)


def market_url(path: str = "/") -> str:
    return app_url("market", path)


def cart_url(path: str = "/") -> str:
    return app_url("cart", path)


def events_url(path: str = "/") -> str:
    return app_url("events", path)


def market_url_for(market_slug: str, path: str = "/") -> str:
    if not path.startswith("/"):
        path = "/" + path
    return market_url(f"/{market_slug}{path}")


def login_url(next_url: str = "") -> str:
    if next_url:
        return coop_url(f"/auth/login/?next={quote(next_url, safe='')}")
    return coop_url("/auth/login/")
