"""
All-markets blueprint — shows markets across ALL pages.

Mounted at / (root of market app). No slug context.
GET / handled by defpage. GET /all-markets is pagination fragment.
"""
from __future__ import annotations

from quart import Blueprint, g, request

from shared.sx.helpers import sx_response
from shared.infrastructure.data_client import fetch_data
from shared.contracts.dtos import PostDTO, dto_from_dict
from shared.services.registry import services


async def _load_markets(page, per_page=20):
    """Load all markets + page info for container badges."""
    markets, has_more = await services.market.list_marketplaces(
        g.s, page=page, per_page=per_page,
    )

    # Batch-load page info for container_ids
    page_info = {}
    if markets:
        post_ids = list({
            m.container_id for m in markets
            if m.container_type == "page"
        })
        if post_ids:
            raw_posts = await fetch_data("blog", "posts-by-ids",
                                         params={"ids": ",".join(str(i) for i in post_ids)},
                                         required=False) or []
            for raw_p in raw_posts:
                p = dto_from_dict(PostDTO, raw_p)
                page_info[p.id] = {"title": p.title, "slug": p.slug}

    return markets, has_more, page_info


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

    @bp.get("/all-markets")
    async def markets_fragment():
        page = int(request.args.get("page", 1))
        markets, has_more, page_info = await _load_markets(page)

        from sxc.pages.renders import render_all_markets_cards
        sx_src = render_all_markets_cards(markets, has_more, page_info, page)
        return sx_response(sx_src)

    return bp
