#!/bin/bash
# 验证状态机定义完整性
# 依赖: go (用于解析 Go 源码)
# 用法: ./verify-state-machine.sh [项目根目录]

set -e

PROJECT_ROOT="${1:-.}"

echo "=== 验证状态机定义 ==="
echo "项目目录: $PROJECT_ROOT"
echo ""

# 基础状态列表
BASE_STATES=(
    "created"
    "pending"
    "assigned"
    "in_progress"
    "pending_review"
    "returned"
    "approved"
    "rejected"
    "revoked"
    "closed"
)

# 扩展状态列表
EXTENDED_STATES=(
    "executing"
    "monitoring"
    "rollbacked"
    "draft_saved"
)

# 终态列表
TERMINAL_STATES=(
    "approved"
    "rejected"
    "revoked"
    "closed"
)

# 事件列表
EVENTS=(
    "submit"
    "auto_assign"
    "assign"
    "accept"
    "reassign"
    "complete"
    "approve"
    "reject"
    "return"
    "resubmit"
    "revoke"
    "close"
)

FAILED=0
PASSED=0
WARNINGS=0

echo "--- 检查基础状态定义 ---"
for state in "${BASE_STATES[@]}"; do
    if grep -rq "\"$state\"" --include="*.go" "$PROJECT_ROOT" 2>/dev/null; then
        echo "[PASS] 状态 '$state' 已定义"
        ((PASSED++))
    else
        echo "[FAIL] 状态 '$state' 未定义"
        ((FAILED++))
    fi
done

echo ""
echo "--- 检查扩展状态定义 ---"
for state in "${EXTENDED_STATES[@]}"; do
    if grep -rq "\"$state\"" --include="*.go" "$PROJECT_ROOT" 2>/dev/null; then
        echo "[PASS] 扩展状态 '$state' 已定义"
        ((PASSED++))
    else
        echo "[WARN] 扩展状态 '$state' 未定义（可选）"
        ((WARNINGS++))
    fi
done

echo ""
echo "--- 检查事件定义 ---"
for event in "${EVENTS[@]}"; do
    if grep -rq "\"$event\"" --include="*.go" "$PROJECT_ROOT" 2>/dev/null; then
        echo "[PASS] 事件 '$event' 已定义"
        ((PASSED++))
    else
        echo "[FAIL] 事件 '$event' 未定义"
        ((FAILED++))
    fi
done

echo ""
echo "--- 检查终态保护 ---"
for state in "${TERMINAL_STATES[@]}"; do
    # 检查是否有 TerminalStates 或 IsTerminal 相关定义
    if grep -rq "Terminal.*$state\|IsTerminal\|终态" --include="*.go" "$PROJECT_ROOT" 2>/dev/null; then
        echo "[PASS] 终态 '$state' 有保护机制"
        ((PASSED++))
    else
        echo "[WARN] 终态 '$state' 可能缺少保护机制"
        ((WARNINGS++))
    fi
done

echo ""
echo "--- 检查撤销权限 ---"
if grep -rq "CanRevoke\|revoke.*Terminal\|IsTerminal" --include="*.go" "$PROJECT_ROOT" 2>/dev/null; then
    echo "[PASS] 撤销权限检查已实现"
    ((PASSED++))
else
    echo "[WARN] 未找到撤销权限检查逻辑"
    ((WARNINGS++))
fi

echo ""
echo "--- 检查乐观锁实现 ---"
if grep -rq "version.*=.*version.*\+.*1\|version.*Expr\|RowsAffected.*==.*0" --include="*.go" "$PROJECT_ROOT" 2>/dev/null; then
    echo "[PASS] 乐观锁机制已实现"
    ((PASSED++))
else
    echo "[FAIL] 未找到乐观锁实现"
    ((FAILED++))
fi

echo ""
echo "--- 检查状态历史记录 ---"
if grep -rq "WorkflowTrackHistory\|workflow_track_history\|TrackHistory" --include="*.go" "$PROJECT_ROOT" 2>/dev/null; then
    echo "[PASS] 状态历史记录已实现"
    ((PASSED++))
else
    echo "[FAIL] 未找到状态历史记录实现"
    ((FAILED++))
fi

echo ""
echo "=== 验证结果 ==="
echo "通过: $PASSED"
echo "警告: $WARNINGS"
echo "失败: $FAILED"

if [ $FAILED -gt 0 ]; then
    echo ""
    echo "请检查并修复失败项"
    exit 1
else
    echo ""
    echo "状态机验证通过！"
    exit 0
fi
