from __future__ import annotations
import path_setup  # noqa: F401
from shared.infrastructure.factory import create_base_app

from bp import register_pages
from services import register_domain_services


async def sx_docs_context() -> dict:
    """SX docs app context processor — fetches cross-service fragments."""
    from quart import request, g
    from shared.infrastructure.context import base_context
    from shared.infrastructure.cart_identity import current_cart_identity
    from shared.infrastructure.fragments import fetch_fragments

    ctx = await base_context()
    ctx["menu_items"] = []

    ident = current_cart_identity()
    user = getattr(g, "user", None)

    cart_params = {}
    if ident.get("user_id"):
        cart_params["user_id"] = ident["user_id"]
    if ident.get("session_id"):
        cart_params["session_id"] = ident["session_id"]

    auth_params = {"email": user.email} if user else None

    cart_mini, auth_menu, nav_tree = await fetch_fragments([
        ("cart", "cart-mini", cart_params or None),
        ("account", "auth-menu", auth_params),
        ("blog", "nav-tree", {"app_name": "sx", "path": request.path}),
    ], required=False)
    ctx["cart_mini"] = cart_mini
    ctx["auth_menu"] = auth_menu
    ctx["nav_tree"] = nav_tree

    return ctx


def create_app() -> "Quart":
    app = create_base_app(
        "sx",
        context_fn=sx_docs_context,
        domain_services_fn=register_domain_services,
    )

    from sxc.pages import setup_sx_pages
    setup_sx_pages()

    bp = register_pages(url_prefix="/")
    app.register_blueprint(bp)

    from shared.sx.pages import auto_mount_pages
    auto_mount_pages(app, "sx")

    return app


app = create_app()
