"""
Public marketing blueprint for ModuleDesk.
Serves the landing page (/) and pricing page (/pricing) without login.

Every route here exists twice: unprefixed for English (``/pricing``) and under
a language segment for the other shipping languages (``/es/pricing``). Search
engines need one URL per language, and keeping English unprefixed means the
URLs that are already indexed do not move.
"""

from flask import Blueprint, current_app, g

public_bp = Blueprint(
    "public",
    __name__,
    url_prefix="",
    template_folder="templates",
)


@public_bp.url_value_preprocessor
def _pull_lang(endpoint, values):
    """Take the language segment out of the URL before the view is called.

    Views take no `lang` argument — the locale reaches them through
    ``select_locale()``, which reads exactly this value.
    """
    if values is None:
        return
    lang = values.pop("lang", None)
    g.public_lang = lang
    if lang:
        # Carry the choice off the marketing pages: /login and the onboarding
        # flow have no translated URL of their own, so without this a visitor
        # who picked Spanish on /es/ would sign up in English. Only an explicit
        # prefix writes the session — an English visitor on the unprefixed URLs
        # never gets a cookie for this.
        from flask import session as flask_session
        if flask_session.get("locale") != lang:
            flask_session["locale"] = lang


@public_bp.url_defaults
def _keep_lang(endpoint, values):
    """Keep the current language when building links between public pages.

    Without this, a link on /es/ back to the landing page would drop the visitor
    into English.
    """
    if "lang" in values:
        return
    lang = g.get("public_lang")
    if lang and current_app.url_map.is_endpoint_expecting(endpoint, "lang"):
        values["lang"] = lang


from . import routes  # noqa: E402,F401
