"""Load demand_grade rows (expanded one row per category) for the category tree UI."""
from __future__ import annotations

from typing import Any

from supply_infra.db.repositories.demand_grade_category_rel_repo import (
    DemandGradeCategoryRelRepository,
)
from supply_infra.db.repositories.demand_grade_repo import DemandGradeRepository
from supply_infra.db.session import get_session


def list_demand_grades(biz_dt: str | None = None) -> list[dict[str, Any]]:
    """
    Return demand_grade rows joined with demand_grade_category_rel, one row per
    (demand_grade, category_id) pair — mirrors the shape the frontend already
    groups by category_id.

    biz_dt defaults to the latest business date present in demand_grade.
    """
    with get_session() as session:
        resolved_biz_dt = biz_dt or DemandGradeRepository(session).get_latest_biz_dt()
        if not resolved_biz_dt:
            return []
        return DemandGradeCategoryRelRepository(session).list_items_with_category(resolved_biz_dt)
