#!/usr/bin/env python3
"""最短路径自检：两轨与完整分轨不能在同一任务里连跑两种模型。"""
import ast
import sys
from pathlib import Path

if len(sys.argv) > 1:
    if sys.argv[1] in ("-h", "--help"):
        print(__doc__.strip())
        sys.exit(0)
    if sys.argv[1] in ("-v", "--version"):
        print("fenxuan shortest path 1.5.0")
        sys.exit(0)
    print(f"unknown arguments: {sys.argv[1:]}", file=sys.stderr)
    sys.exit(2)

SOURCE = Path(__file__).parents[1] / "server" / "app.py"
text = SOURCE.read_text(encoding="utf-8")
tree = ast.parse(text)


def call_names(nodes):
    names = []
    for node in nodes:
        for child in ast.walk(node):
            if not isinstance(child, ast.Call):
                continue
            func = child.func
            if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name):
                names.append(f"{func.value.id}.{func.attr}")
    return names


profiles = next(node for node in tree.body
                if isinstance(node, ast.Assign)
                and any(isinstance(target, ast.Name) and target.id == "PROFILES"
                        for target in node.targets))
assert set(ast.literal_eval(profiles.value)) == {"vocal", "stems6"}

pipeline = next(node for node in tree.body
                if isinstance(node, ast.FunctionDef) and node.name == "run_pipeline")
route = next(node for node in ast.walk(pipeline)
             if isinstance(node, ast.If)
             and isinstance(node.test, ast.Compare)
             and isinstance(node.test.left, ast.Name)
             and node.test.left.id == "profile"
             and isinstance(node.test.ops[0], ast.Eq)
             and isinstance(node.test.comparators[0], ast.Constant)
             and node.test.comparators[0].value == "vocal")
vocal_calls = call_names(route.body)
stems_calls = call_names(route.orelse)
assert "sep.separate_roformer" in vocal_calls and "sep.separate" not in vocal_calls
assert "sep.separate" in stems_calls and "sep.separate_roformer" not in stems_calls
assert "ZipFile" not in call_names(pipeline.body)
for removed in ('"stems4"', '"/api/refine"', '"/api/tracks-zip/{job_id}"'):
    assert removed not in text

print("SHORT_PATH: PASS (one task, one model)")
