"""Build grouped summaries from normalized report records."""


def build_report(records: list[dict]) -> str:
    if not records:
        return "Report is empty (0 items)"

    grouped: dict[str, dict[str, float | int]] = {}
    for record in records:
        label = record.get("group_label") or "Unknown"
        bucket = grouped.setdefault(label, {"count": 0, "total": 0.0})
        bucket["count"] += 1
        bucket["total"] += float(record.get("line_total", 0.0))

    lines = []
    for label, stats in grouped.items():
        item_word = "item" if stats["count"] == 1 else "items"
        lines.append(
            f"Team: {label} | {stats['count']} {item_word} | ${stats['total']:.2f}"
        )

    return "\n".join(lines)
