"""Group individual TicketDTOs by (entry_id, ticket_type_id) for cart display."""
from __future__ import annotations

from collections import OrderedDict


def group_tickets(tickets) -> list[dict]:
    """
    Group a flat list of TicketDTOs into aggregate rows.

    Returns list of dicts:
        {
            "entry_id": int,
            "entry_name": str,
            "entry_start_at": datetime,
            "entry_end_at": datetime | None,
            "ticket_type_id": int | None,
            "ticket_type_name": str | None,
            "price": Decimal | None,
            "quantity": int,
            "line_total": float,
        }
    """
    groups: OrderedDict[tuple, dict] = OrderedDict()

    for tk in tickets:
        key = (tk.entry_id, getattr(tk, "ticket_type_id", None))
        if key not in groups:
            groups[key] = {
                "entry_id": tk.entry_id,
                "entry_name": tk.entry_name,
                "entry_start_at": tk.entry_start_at,
                "entry_end_at": tk.entry_end_at,
                "ticket_type_id": getattr(tk, "ticket_type_id", None),
                "ticket_type_name": tk.ticket_type_name,
                "price": tk.price,
                "quantity": 0,
                "line_total": 0,
            }
        groups[key]["quantity"] += 1
        groups[key]["line_total"] += float(tk.price or 0)

    return list(groups.values())
