"""守卫 gate tree 错配 bug：run_gates 必须用 current_tree（换视频后的当前树）。"""

import ast
from pathlib import Path

_PIPELINE = Path(__file__).resolve().parents[2] / "app" / "question_gen" / "pipeline_v2.py"


def _find_run_gates_tree_arg() -> str:
    """解析 pipeline_v2.py，返回 run_gates 调用中 tree= 关键字实参的变量名。"""
    tree_src = ast.parse(_PIPELINE.read_text(encoding="utf-8"))
    for node in ast.walk(tree_src):
        if isinstance(node, ast.Call):
            func = node.func
            name = getattr(func, "id", None) or getattr(func, "attr", None)
            if name == "run_gates":
                for kw in node.keywords:
                    if kw.arg == "tree":
                        assert isinstance(kw.value, ast.Name)
                        return kw.value.id
    raise AssertionError("未找到 run_gates 的 tree= 关键字实参")


def test_run_gates_uses_current_tree():
    assert _find_run_gates_tree_arg() == "current_tree"
