#!/bin/bash
# verify-k8s-ops.sh - K8S操作实现验证脚本
# 依赖: go 1.21+
# 用法: ./verify-k8s-ops.sh [watchdog_dir]

set -e

WATCHDOG_DIR="${1:-./rmdc-watchdog}"

echo "=== K8S 操作实现验证 ==="
echo "目标目录: $WATCHDOG_DIR"
echo ""

# 1. 检查K8S客户端文件
echo "[1/4] 检查K8S客户端..."
K8S_CLIENT="$WATCHDOG_DIR/pkg/k8s/client.go"
if [ -f "$K8S_CLIENT" ]; then
    echo "✓ K8S客户端文件存在: $K8S_CLIENT"
else
    echo "✗ K8S客户端文件不存在"
fi

# 2. 验证操作白名单
echo ""
echo "[2/4] 验证K8S操作白名单..."
K8S_SERVICE="$WATCHDOG_DIR/internal/service/k8s_service.go"
ALLOWED_ACTIONS="logs exec scale restart delete get apply"

if [ -f "$K8S_SERVICE" ]; then
    echo "检查 $K8S_SERVICE:"
    for action in $ALLOWED_ACTIONS; do
        if grep -q "case \"$action\"" "$K8S_SERVICE" 2>/dev/null; then
            echo "  ✓ '$action' 已实现"
        else
            echo "  ⚠ '$action' 未找到"
        fi
    done
else
    echo "⚠ K8S服务文件不存在: $K8S_SERVICE"
fi

# 3. 验证超时处理
echo ""
echo "[3/4] 验证超时处理..."
if grep -rq "context.WithTimeout\|WithDeadline" "$WATCHDOG_DIR/pkg/k8s/" 2>/dev/null; then
    echo "✓ 找到超时控制实现"
else
    echo "⚠ 未找到超时控制，请确认K8S调用设置了timeout"
fi

# 4. 验证结果结构
echo ""
echo "[4/4] 验证ExecResult结构..."
if grep -rq "ExecResult" "$WATCHDOG_DIR" --include="*.go" 2>/dev/null; then
    echo "✓ 找到ExecResult定义"

    # 检查必要字段
    REQUIRED_FIELDS="CommandID Status ExitCode Output Duration"
    for field in $REQUIRED_FIELDS; do
        if grep -rq "$field" "$WATCHDOG_DIR" --include="*.go" 2>/dev/null | grep -q "ExecResult\|exec_result"; then
            echo "  ✓ 字段 '$field' 存在"
        else
            echo "  ⚠ 字段 '$field' 未找到"
        fi
    done
else
    echo "⚠ 未找到ExecResult定义"
fi

# 5. 运行测试
echo ""
echo "[5/5] 运行K8S相关测试..."
cd "$WATCHDOG_DIR"
if go test ./pkg/k8s/... -v 2>&1 | head -20; then
    echo "✓ K8S测试执行完成"
else
    echo "⚠ K8S测试执行有问题"
fi

echo ""
echo "=== 验证完成 ==="
