"""
按分类 id 查询从根到节点的类目路径，用于写 reason。
"""
from __future__ import annotations

import logging
from typing import Any

from agents.demand_grade_agent.tools.shared import build_category_path
from supply_agent.tools import tool
from supply_infra.db.repositories.global_tree_category_repo import (
    GlobalTreeCategoryRepository,
)
from supply_infra.db.session import get_session

logger = logging.getLogger(__name__)


def _normalize_ids(category_ids: list[Any]) -> tuple[list[int], str | None]:
    if not category_ids:
        return [], "category_ids 不能为空"
    out: list[int] = []
    seen: set[int] = set()
    for raw in category_ids:
        try:
            cid = int(raw)
        except (TypeError, ValueError):
            return [], f"category_ids 含无效 id: {raw!r}"
        if cid in seen:
            continue
        seen.add(cid)
        out.append(cid)
    if not out:
        return [], "category_ids 不能为空"
    return out, None


@tool
def query_category_path(category_ids: list[int]) -> str:
    """
    查询分类节点从根到自身的名称路径，用于写 reason。

    Args:
        category_ids: 分类 id 列表（可多个）。

    Returns:
        每行一条路径，例如：
        [88] 美食 > 减脂饮食 > 加餐
        [128] 美妆护肤 > 护肤 > 精华
    """
    ids, err = _normalize_ids(category_ids)
    if err:
        return err

    try:
        with get_session() as session:
            categories = GlobalTreeCategoryRepository(session).list_active_categories()
            by_id = {int(c.id): c for c in categories}

            lines: list[str] = []
            for cid in ids:
                path = build_category_path(cid, by_id)
                if path is None:
                    lines.append(f"[{cid}] （未找到该分类）")
                else:
                    lines.append(f"[{cid}] {path}")

        logger.info("query_category_path completed: ids=%s", ids)
        return "\n".join(lines)

    except Exception as e:
        logger.error("query_category_path failed: %s", e, exc_info=True)
        return f"查询分类路径失败: {e}"


def main() -> None:
    print(query_category_path(category_ids=[1, 2]))


if __name__ == "__main__":
    main()
