"""
按需求词粒度直接查询 demand_popularity_stats，作为树节点粒度数据的交叉验证。
"""
from __future__ import annotations

import logging
from typing import Optional

from sqlalchemy.orm import Session

from agents.demand_grade_agent.tools.shared import (
    format_posterior_dim_with_count,
    normalize_biz_dt,
    normalize_str_list,
)
from supply_agent.tools import tool
from supply_infra.db.repositories.demand_popularity_stats_repo import (
    DemandPopularityStatsRepository,
)
from supply_infra.db.session import get_session

logger = logging.getLogger(__name__)


def _query_one_demand_popularity_by_word(
    session: Session,
    keyword: str,
    normalized_dt: str | None,
) -> str:
    rows = DemandPopularityStatsRepository(session).search_by_word_name(keyword, normalized_dt)

    if not rows:
        dt_note = f"biz_dt={normalized_dt}" if normalized_dt else "任意业务日"
        return f"「{keyword}」在 demand_popularity_stats（{dt_note}）无匹配数据"

    lines = []
    for row in rows:
        posterior_note = "有后验数据" if row.real_rov_7d_count > 0 else "无后验数据(效果未知)"
        lines.append(
            f"[biz_dt={row.biz_dt}] {row.demand_word_name}: "
            f"后验rov_diff={format_posterior_dim_with_count(row.real_rov_7d_avg, row.real_rov_7d_count)} "
            f"后验vov_diff={format_posterior_dim_with_count(row.real_vov_7d_avg, row.real_vov_7d_count)} "
            f"({posterior_note})"
        )
    return "\n".join(lines)


@tool
def query_demand_popularity_by_word(
    demand_word_names: list[str],
    biz_dt: Optional[str] = None,
) -> str:
    """
    按需求词名（精确+模糊）查询 demand_popularity_stats 的词粒度效果数据。

    支持批量传入多个需求词，一次调用返回各词的统计；每段结果前会标注原始 demand_word_name。

    demand_popularity_stats 比 category_tree_weight 粒度更细（按具体需求词而非整个树节点），
    可用于交叉验证 query_demand_category_and_weight 给出的树节点级结论，
    也可用于发现措辞相近但独立统计的近似词数据。

    Args:
        demand_word_names: 需求词名称或关键片段列表，可一次传多个。
        biz_dt: 业务日期 YYYYMMDD，可选；不传则不限日期，按业务日降序列出（可能有多天历史数据）。

    Returns:
        每个 demand_word_name 一段，段首标注 `--- demand_word_name: xxx ---`，例如：
        --- demand_word_name: 减脂期加餐 ---
        [biz_dt=20260716] 减脂期加餐: 后验rov_diff=0.0500(n=5) [效果非常好] 后验vov_diff=-0.0800(n=5) [可接受] (有后验数据)
    """
    normalized_dt, err = normalize_biz_dt(biz_dt)
    if err:
        return err

    names, err = normalize_str_list(demand_word_names, "demand_word_names")
    if err:
        return err

    try:
        with get_session() as session:
            sections: list[str] = []
            for keyword in names:
                result = _query_one_demand_popularity_by_word(session, keyword, normalized_dt)
                sections.append(f"--- demand_word_name: {keyword} ---\n{result}")

        message = "\n\n".join(sections)
        logger.info(
            "query_demand_popularity_by_word completed: count=%d biz_dt=%s",
            len(names),
            normalized_dt,
        )
        return message

    except Exception as e:
        logger.error("query_demand_popularity_by_word failed: %s", e, exc_info=True)
        return f"查询需求词热度统计失败: {e}"


def main() -> None:
    print(query_demand_popularity_by_word(demand_word_names=["加餐", "减脂期加餐"]))


if __name__ == "__main__":
    main()
