"""以层级文本展示当天未分批分类节点所在的全局树及原始热度分。"""
from __future__ import annotations

from agents.demand_grade_orchestrator_agent.common.assignment import get_unassigned_hanging_category_ids
from agents.demand_grade_orchestrator_agent.common import (
    format_demand_count,
    format_heat_score,
    format_rank,
    global_heat_positions,
    has_hung_demand,
    heat_level,
    load_tree_state,
)
from supply_agent.tools import tool


@tool
def query_global_heat_tree(biz_dt: str) -> str:
    """返回未分批节点及其祖先路径；+ 与需求数仅展示未分批节点自身。"""
    by_id, children, weights = load_tree_state(biz_dt)
    positions = global_heat_positions(weights)
    unassigned_nodes = get_unassigned_hanging_category_ids(biz_dt)
    visible_cache: dict[int, bool] = {}

    def visible(category_id: int) -> bool:
        if category_id in visible_cache:
            return visible_cache[category_id]
        value = category_id in unassigned_nodes or any(
            visible(child) for child in children.get(category_id, [])
        )
        visible_cache[category_id] = value
        return value

    lines = [
        f"biz_dt={biz_dt} | 格式：[分类ID]分类名称[total_score|整树名次|热度等级|需求数] + | "
        "仅展示未分批节点及其祖先路径；+ 与需求数仅对未分批且有挂载需求的节点展示；"
        "名次在整棵有分节点中计算；无数据为 null/U"
    ]

    def render(category_id: int, depth: int) -> None:
        if not visible(category_id):
            return
        category = by_id[category_id]
        weight = weights.get(category_id)
        score_text = format_heat_score(weight)
        position = positions.get(category_id)
        is_unassigned = category_id in unassigned_nodes
        demand_count = format_demand_count(weight) if is_unassigned and has_hung_demand(weight) else ""
        demand_suffix = f"|{demand_count}" if demand_count else ""
        suffix = " +" if is_unassigned and has_hung_demand(weight) else ""
        lines.append(
            f"{'  ' * depth}[{category_id}]{category.name or ''}"
            f"[{score_text}|{format_rank(position)}|{heat_level(position)}{demand_suffix}]{suffix}"
        )
        for child in children.get(category_id, []):
            render(child, depth + 1)

    for root_id in children.get(None, []):
        render(root_id, 0)
    if len(lines) == 1:
        return f"biz_dt={biz_dt} 无未分批的有需求分类节点"
    lines.append(f"未分批节点数={len(unassigned_nodes)}")
    return "\n".join(lines)


if __name__ == '__main__':
    res = query_global_heat_tree('20260714')
    print(res)
