"""Pattern: assemble context from several memory tiers under one budget.

A typical prompt mixes: instructions, a user profile, retrieved long-term
memories, a running summary, and recent turns. Give each section a priority
and a cap; fill in priority order; trim the lowest-priority sections first.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Callable

from .tokens import count_tokens


@dataclass
class Section:
    title: str
    items: list[str]
    priority: int = 0          # higher is filled first
    max_tokens: int | None = None


def build_context(sections: list[Section], budget: int,
                  counter: Callable[[str], int] = count_tokens) -> str:
    """Render sections as Markdown, filling higher-priority sections first.

    Items within a section are assumed to be ordered best-first; items that do not
    fit are dropped. Output keeps the original section order for readability.
    """
    remaining = budget
    chosen: dict[int, list[str]] = {}
    order = sorted(range(len(sections)), key=lambda i: -sections[i].priority)
    for i in order:
        sec = sections[i]
        header_cost = counter(f"## {sec.title}\n")
        if header_cost >= remaining:
            continue
        cap = remaining - header_cost
        if sec.max_tokens is not None:
            cap = min(cap, sec.max_tokens)
        picked, used = [], 0
        for item in sec.items:
            cost = counter(f"- {item}\n")
            if used + cost > cap:
                continue
            picked.append(item)
            used += cost
        if picked:
            chosen[i] = picked
            remaining -= header_cost + used
    parts = []
    for i, sec in enumerate(sections):
        if i in chosen:
            parts.append(f"## {sec.title}\n" + "\n".join(f"- {it}" for it in chosen[i]))
    return "\n\n".join(parts)
