"""query demo 离线测：①②纯逻辑 + 树采样 + parse_suggest（不碰网络/LLM）。"""
from __future__ import annotations

import pytest

from acquisition.query import (
    CARRIER_POS, CARRIER_POS_GROUPED, KTYPE_SUFFIX, _nonleaf_d4, sample_nodes,
    tactic_multiaxis,
)
from acquisition.suggest import SuggestError, parse_suggest


def test_sample_nodes():
    topics = sample_nodes("实质", limit=8)
    forms = sample_nodes("形式", limit=8)
    assert 0 < len(topics) <= 8 and 0 < len(forms) <= 8
    assert all(isinstance(x, str) and x for x in topics + forms)


def test_carrier_pos_and_form_sampling():
    # ② 的载体位置 = 载体×位置交叉；文章无封面；形式树（架构分支）可采样
    assert "短视频开头" in CARRIER_POS and "图片封面" in CARRIER_POS
    assert "文章封面" not in CARRIER_POS            # 文章无封面
    assert CARRIER_POS_GROUPED["文章"] == ["开头", "中间", "收尾"]
    forms = sample_nodes("形式", under="架构", depths=(4,), limit=8)
    assert 0 < len(forms) <= 8 and all(isinstance(f, str) and f for f in forms)


def test_parse_suggest_mines_tags_and_titles():
    resp = {"code": 0, "data": {"data": [
        {"title": "健身脚本怎么写 #健身 #跟练脚本", "body_text": "教程 #减脂",
         "topic_list": [{"name": "健身博主"}]},
    ]}}
    out = parse_suggest(resp, limit=10)
    assert "健身" in out and "跟练脚本" in out and "减脂" in out and "健身博主" in out


def test_multiaxis_assembly():
    rows = tactic_multiaxis(n=12)
    assert len(rows) == 12
    r = rows[0]
    assert {"实质", "形式", "阶段", "动作", "作用", "知识类型", "query"} <= set(r)
    # 形式限架构：不应混进 剪辑/后期 等制作节点
    forms = _nonleaf_d4("形式", 6, under="架构")
    assert "剪辑组接" not in forms and "后期处理" not in forms
    # 组合 query = 各轴机械拼接，句尾是知识类型后缀
    assert r["query"].startswith(r["实质"] + " " + r["形式"])
    assert r["query"].endswith(KTYPE_SUFFIX[r["知识类型"]])


def test_parse_suggest_business_error():
    with pytest.raises(SuggestError):
        parse_suggest({"code": 10000, "msg": "x"})
