#!/usr/bin/env python3
from pathlib import Path
import sys


ENTRY_ROOT = Path(__file__).resolve().parents[4]
SKILLS_ROOT = ENTRY_ROOT.parent
WORKFLOW_ROOT = ENTRY_ROOT / "references" / "methods" / "workflow-orchestrator"


def require_text(path: Path, required: list[str]) -> list[str]:
    if not path.is_file():
        return [f"missing file: {path}"]
    content = path.read_text(encoding="utf-8")
    return [f"{path}: missing {item!r}" for item in required if item not in content]


def main() -> int:
    errors: list[str] = []

    errors += require_text(
        ENTRY_ROOT / "SKILL.md",
        ["SA flow", "workflow-orchestrator", "根据用户意图选择最匹配的方法"],
    )

    errors += require_text(
        WORKFLOW_ROOT / "METHOD.md",
        [
            "clarifying",
            "awaiting_decision",
            "Observe → Decide → Act → Verify → Repeat",
            "references/stage-contract.md",
            "失败后的未执行阶段必须标记为 `skipped`",
            "impact_surface",
            "uncovered_scope",
            "residual_risks",
        ],
    )

    errors += require_text(
        WORKFLOW_ROOT / "references" / "stage-contract.md",
        ["completed | blocked | failed | skipped", "next_need", "verification", "impact_surface", "uncovered_scope", "residual_risks"],
    )

    errors += require_text(
        WORKFLOW_ROOT / "references" / "acceptance-scenarios.md",
        [
            "## S0 隐式闭环",
            "## S0.2 产品与技术调研",
            "## S1 模糊需求",
            "## S2 明确 Bug",
            "## S3 跨模块重构",
            "## S4 高风险动作",
            "## S5 阶段失败",
            "## S6 目标完成",
            "clarifying",
            "awaiting_decision",
            "skipped",
            "completed",
        ],
    )

    methods = [
        "project-context",
        "product-research",
        "clarify-requirements",
        "architecture-review",
        "design-research",
        "decompose-tasks",
        "execute-plan",
        "debug-issues",
        "code-review",
        "review-feedback",
        "resume-task",
        "verify-complete",
    ]
    for method in methods:
        errors += require_text(
            ENTRY_ROOT / "references" / "methods" / method / "METHOD.md",
            ["## Workflow 交接", "workflow-orchestrator"],
        )

    if errors:
        print("SA Flow contract validation failed:")
        for error in errors:
            print(f"- {error}")
        return 1

    print("SA Flow contract validation passed")
    print(f"Validated {len(methods)} workflow methods")
    return 0


if __name__ == "__main__":
    sys.exit(main())
