"""
Page-markets blueprint — shows markets for a single page.

Mounted at /<slug> (page-scoped). Requires g.post_data from hydrate_post.
GET / handled by defpage. GET /page-markets is pagination fragment.
"""
from __future__ import annotations

from quart import Blueprint, g, request

from shared.sx.helpers import sx_response
from shared.services.registry import services


async def _load_markets(post_id, page, per_page=20):
    """Load markets for this page's container."""
    markets, has_more = await services.market.list_marketplaces(
        g.s, "page", post_id, page=page, per_page=per_page,
    )
    return markets, has_more


def register() -> Blueprint:
    bp = Blueprint("page_markets", __name__)

    @bp.get("/page-markets")
    async def markets_fragment():
        post = g.post_data["post"]
        page = int(request.args.get("page", 1))

        markets, has_more = await _load_markets(post["id"], page)

        from sxc.pages.renders import render_page_markets_cards
        post_slug = post.get("slug", "")
        sx_src = render_page_markets_cards(markets, has_more, page, post_slug)
        return sx_response(sx_src)

    return bp
