#!/bin/bash
# verify-project-module.sh
# 验证 rmdc-project-management 模块的完整性
# 依赖: go, grep, find
# 用法: ./verify-project-module.sh [project-root-path]

set -e

PROJECT_ROOT="${1:-.}"

echo "=========================================="
echo "RMDC Project Management Module Verification"
echo "=========================================="
echo "Project Root: $PROJECT_ROOT"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

PASS_COUNT=0
FAIL_COUNT=0
WARN_COUNT=0

check_pass() {
    echo -e "${GREEN}[PASS]${NC} $1"
    ((PASS_COUNT++))
}

check_fail() {
    echo -e "${RED}[FAIL]${NC} $1"
    ((FAIL_COUNT++))
}

check_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
    ((WARN_COUNT++))
}

# 1. 检查实体定义
echo "1. Checking Entity Definitions..."
if grep -rq "LifecycleStatus" "$PROJECT_ROOT"/internal/project/entity/*.go 2>/dev/null; then
    check_pass "LifecycleStatus field exists in Project entity"
else
    check_fail "LifecycleStatus field missing in Project entity"
fi

if grep -rq "CurrentVersion" "$PROJECT_ROOT"/internal/project/entity/*.go 2>/dev/null; then
    check_pass "CurrentVersion field exists for version tracking"
else
    check_fail "CurrentVersion field missing for version tracking"
fi

if grep -rq "CertificationStatus" "$PROJECT_ROOT"/internal/project/entity/*.go 2>/dev/null; then
    check_pass "CertificationStatus field exists"
else
    check_fail "CertificationStatus field missing"
fi

# 2. 检查生命周期状态常量
echo ""
echo "2. Checking Lifecycle Status Constants..."
REQUIRED_STATES=("INIT" "DRAFTING" "REVIEWING" "RELEASED" "MODIFYING" "ARCHIVED")
for state in "${REQUIRED_STATES[@]}"; do
    if grep -rq "\"$state\"" "$PROJECT_ROOT"/internal/project/ 2>/dev/null; then
        check_pass "Lifecycle state '$state' defined"
    else
        check_fail "Lifecycle state '$state' not found"
    fi
done

# 3. 检查 API 路由
echo ""
echo "3. Checking API Routes..."
REQUIRED_ROUTES=(
    "/api/project/list"
    "/api/project/detail"
    "/api/project/create"
    "/api/project/update"
    "/api/project/draft/save"
    "/api/project/draft/submit"
    "/api/project/version/list"
    "/api/project/permission/grant"
)
for route in "${REQUIRED_ROUTES[@]}"; do
    if grep -rq "$route" "$PROJECT_ROOT"/internal/project/ 2>/dev/null; then
        check_pass "Route '$route' registered"
    else
        check_fail "Route '$route' not found"
    fi
done

# 4. 检查权限中间件
echo ""
echo "4. Checking Permission Middleware..."
if grep -rq "SuperAdmin\|RequireRole\|RequirePermission" "$PROJECT_ROOT"/internal/project/handler/*.go 2>/dev/null; then
    check_pass "Permission middleware applied"
else
    check_warn "Permission middleware not detected - verify manually"
fi

# 5. 检查版本服务
echo ""
echo "5. Checking Version Service..."
if grep -rq "CompareVersions" "$PROJECT_ROOT"/internal/project/service/*.go 2>/dev/null; then
    check_pass "Version comparison service implemented"
else
    check_fail "Version comparison service not found"
fi

if grep -rq "CreateOfficialVersion" "$PROJECT_ROOT"/internal/project/service/*.go 2>/dev/null; then
    check_pass "CreateOfficialVersion method exists"
else
    check_fail "CreateOfficialVersion method not found"
fi

# 6. 检查回调接口
echo ""
echo "6. Checking Lifecycle Callback Interface..."
if grep -rq "ProjectLifecycleUpdater" "$PROJECT_ROOT"/internal/project/*.go 2>/dev/null; then
    check_pass "ProjectLifecycleUpdater interface defined"
else
    check_fail "ProjectLifecycleUpdater interface not found"
fi

CALLBACK_METHODS=("SetLifecycleToDrafting" "SetLifecycleToReviewing" "SetLifecycleToReleased" "SetLifecycleToModifying")
for method in "${CALLBACK_METHODS[@]}"; do
    if grep -rq "$method" "$PROJECT_ROOT"/internal/project/ 2>/dev/null; then
        check_pass "Callback method '$method' implemented"
    else
        check_fail "Callback method '$method' not found"
    fi
done

# 7. 检查敏感字段加密
echo ""
echo "7. Checking Sensitive Field Encryption..."
if grep -rq "Encrypt\|Decrypt\|AES\|crypto" "$PROJECT_ROOT"/internal/project/service/*.go 2>/dev/null; then
    check_pass "Encryption functions detected"
else
    check_warn "Encryption functions not detected - verify password field handling"
fi

# 8. 检查审计日志集成
echo ""
echo "8. Checking Audit Log Integration..."
if grep -rq "audit\|AuditService\|auditSvc" "$PROJECT_ROOT"/internal/project/service/*.go 2>/dev/null; then
    check_pass "Audit log integration detected"
else
    check_warn "Audit log integration not detected - verify manually"
fi

# 9. 检查乐观锁实现
echo ""
echo "9. Checking Optimistic Lock..."
if grep -rq "base_version\|BaseVersion\|VersionConflict" "$PROJECT_ROOT"/internal/project/ 2>/dev/null; then
    check_pass "Optimistic lock (version conflict check) implemented"
else
    check_warn "Optimistic lock not detected - concurrent modification may cause issues"
fi

# 10. 运行单元测试（如果可用）
echo ""
echo "10. Running Unit Tests..."
if [ -d "$PROJECT_ROOT/internal/project" ]; then
    cd "$PROJECT_ROOT"
    if go test ./internal/project/... -v -short -count=1 2>&1 | head -20; then
        check_pass "Unit tests executed"
    else
        check_warn "Unit tests may have issues - check output above"
    fi
else
    check_warn "Project directory not found, skipping tests"
fi

# 11. 检查编译
echo ""
echo "11. Checking Build..."
if [ -d "$PROJECT_ROOT/internal/project" ]; then
    cd "$PROJECT_ROOT"
    if go build ./internal/project/... 2>/dev/null; then
        check_pass "Module compiles successfully"
    else
        check_fail "Module compilation failed"
    fi
else
    check_warn "Project directory not found, skipping build check"
fi

# 12. 检查 JSONB 字段定义
echo ""
echo "12. Checking JSONB Field Definitions..."
JSONB_FIELDS=("basic_info" "deploy_business" "deploy_env" "deploy_middleware")
for field in "${JSONB_FIELDS[@]}"; do
    if grep -rq "\"$field\"" "$PROJECT_ROOT"/internal/project/entity/*.go 2>/dev/null; then
        check_pass "JSONB field '$field' defined"
    else
        check_fail "JSONB field '$field' not found"
    fi
done

# 总结
echo ""
echo "=========================================="
echo "Verification Summary"
echo "=========================================="
echo -e "Passed:  ${GREEN}$PASS_COUNT${NC}"
echo -e "Failed:  ${RED}$FAIL_COUNT${NC}"
echo -e "Warnings: ${YELLOW}$WARN_COUNT${NC}"

if [ $FAIL_COUNT -gt 0 ]; then
    echo ""
    echo -e "${RED}Some checks failed. Please review and fix the issues.${NC}"
    echo ""
    echo "Common fixes:"
    echo "  - Missing lifecycle states: Add constants in entity/constants.go"
    echo "  - Missing routes: Register in handler/router.go"
    echo "  - Missing callback interface: Implement ProjectLifecycleUpdater"
    echo "  - Missing version service: Implement version comparison logic"
    exit 1
elif [ $WARN_COUNT -gt 0 ]; then
    echo ""
    echo -e "${YELLOW}Some warnings detected. Please verify manually.${NC}"
    exit 0
else
    echo ""
    echo -e "${GREEN}All checks passed!${NC}"
    exit 0
fi
