#!/bin/bash
# set -eo pipefail

# 测试配置
TEST_REPEATS=2
AGENT_BIN="/usr/local/bin/agent-wdd"  # 修正路径拼写错误

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

# 测试统计
declare -i TOTAL_TESTS=0 PASSED_TESTS=0 FAILED_TESTS=0

# 实用函数
log() {
  echo -e "${YELLOW}[INFO] $* ${NC}"
}

pass() {
  echo -e "${GREEN}PASS: $* ${NC}"
  ((PASSED_TESTS++))
  ((TOTAL_TESTS++))
}

fail() {
  echo -e "${RED}FAIL: $* ${NC}"
  ((FAILED_TESTS++))
  ((TOTAL_TESTS++))
}

test_command() {
  local cmd="$1"
  local expected="${2:-0}"

  if ! eval "$cmd"; then
    local exit_code=$?
    [[ $exit_code -eq "$expected" ]] || {
      fail "$cmd (exit $exit_code)"
      return 1
    }
  fi
  pass "$cmd"
  return 0
}

repeat_test() {
  local times=$1
  local cmd="$2"
  local expected="${3:-0}"

  for ((i=1; i<=times; i++)); do
    test_command "$cmd" "$expected"
  done
}

test_base_docker() {
  log "\nTesting Docker commands..."
  test_command "$AGENT_BIN base docker remove" 0
  test_command "$AGENT_BIN base docker online" 0
  repeat_test $TEST_REPEATS "$AGENT_BIN base docker local" 0

  if docker --version >/dev/null 2>&1; then
    pass "docker installation"
  else
    fail "docker installation"
  fi
}

test_base_ssh() {
  log "\nTesting SSH commands..."
  repeat_test $TEST_REPEATS "$AGENT_BIN base ssh port 2222" 0
  test_command "$AGENT_BIN base ssh config" 0
}

test_tools() {
  log "\nTesting tools installation..."
  local tools=("htop" "tmux" "nano")
  for tool in "${tools[@]}"; do
    if command -v "$tool" >/dev/null 2>&1; then
      pass "$tool already installed"
    else
      test_command "$AGENT_BIN base tools $tool" 0
    fi
  done
}

test_info_commands() {
  log "\nTesting info commands..."
  local commands=(
    "$AGENT_BIN info all"
    "$AGENT_BIN info cpu"
    "$AGENT_BIN info disk"
    "$AGENT_BIN info mem"
    "$AGENT_BIN info network"
    "$AGENT_BIN info os"
  )

  for cmd in "${commands[@]}"; do
    repeat_test $TEST_REPEATS "$cmd" 0
  done
}

main() {
  # 前置检查
  [[ -x "$AGENT_BIN" ]] || {
    log "Error: Agent binary not found or not executable: $AGENT_BIN"
    exit 1
  }

  log "Starting tests with $AGENT_BIN..."
  
  # 基本信息测试
  test_command "$AGENT_BIN version" 0
  test_command "$AGENT_BIN help" 0
  
  # 基础模块测试
  test_base_docker
  test_base_ssh
  test_tools
  
  # 信息模块测试
  test_info_commands

  log "\nTest Summary:"
  echo -e "Total Tests: $TOTAL_TESTS"
  echo -e "${GREEN}Passed: $PASSED_TESTS ${NC}"
  echo -e "${RED}Failed: $FAILED_TESTS ${NC}"
  
  exit "$FAILED_TESTS"
}

main
