#!/usr/bin/env bash

# test_helper.bash - BATS测试辅助函数
# Copyright (c) 2025 TaskSentinel
# MIT License

# 测试环境配置
export BATS_TEST_DIRNAME="${BATS_TEST_DIRNAME:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"
export PROJECT_ROOT="$(cd "$BATS_TEST_DIRNAME/.." && pwd)"
export SCRIPTS_DIR="$PROJECT_ROOT/scripts"
export CONFIG_DIR="$PROJECT_ROOT/config"
export TASKSENTRY_SCRIPT="$SCRIPTS_DIR/tasksentry.sh"

# 测试临时目录
export TEST_TEMP_DIR="${BATS_TMPDIR:-/tmp}/tasksentry_test_$$"

# 创建测试环境
setup_test_environment() {
    # 创建临时测试目录
    mkdir -p "$TEST_TEMP_DIR"
    
    # 设置测试配置文件路径
    export TEST_CONFIG="$TEST_TEMP_DIR/test_config.json"
    
    # 创建测试用的默认配置
    create_test_config
}

# 清理测试环境
teardown_test_environment() {
    # 清理临时文件
    if [[ -d "$TEST_TEMP_DIR" ]]; then
        rm -rf "$TEST_TEMP_DIR"
    fi
}

# 创建测试配置文件
create_test_config() {
    cat > "$TEST_CONFIG" << 'EOF'
{
  "platform": "dingtalk",
  "webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=test_token",
  "secret": "SEC_test_secret",
  "format": "markdown",
  "debug": true,
  "throttle_seconds": 0
}
EOF
}

# 创建企业微信测试配置
create_wechat_test_config() {
    cat > "$TEST_CONFIG" << 'EOF'
{
  "platform": "wechat",
  "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test_key",
  "format": "text",
  "debug": true,
  "throttle_seconds": 0
}
EOF
}

# 创建有效的配置文件
create_valid_config() {
    local config_file="$1"
    cat > "$config_file" << 'EOF'
{
  "platform": "dingtalk",
  "webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=test_token",
  "secret": "SEC_test_secret",
  "format": "markdown",
  "debug": false,
  "throttle_seconds": 60
}
EOF
}

# 创建无效的测试配置文件
create_invalid_test_config() {
    cat > "$TEST_CONFIG" << 'EOF'
{
  "platform": "dingtalk",
  "webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=test_token"
  "secret": "SEC_test_secret",
EOF
}

# 运行tasksentry.sh脚本的包装函数
run_tasksentry() {
    run "$TASKSENTRY_SCRIPT" "$@"
}

# 运行tasksentry.sh脚本并指定配置文件
run_tasksentry_with_config() {
    local config_file="$1"
    shift
    run "$TASKSENTRY_SCRIPT" --config "$config_file" "$@"
}

# 断言命令成功执行
assert_success() {
    if [[ "$status" -ne 0 ]]; then
        echo "Expected success but got exit code: $status"
        echo "Output: $output"
        return 1
    fi
}

# 断言命令执行失败
assert_failure() {
    if [[ "$status" -eq 0 ]]; then
        echo "Expected failure but command succeeded"
        echo "Output: $output"
        return 1
    fi
}

# 断言输出包含指定文本
assert_output_contains() {
    local expected="$1"
    if [[ "$output" != *"$expected"* ]]; then
        echo "Expected output to contain: $expected"
        echo "Actual output: $output"
        return 1
    fi
}

# 断言输出不包含指定文本
assert_output_not_contains() {
    local unexpected="$1"
    if [[ "$output" == *"$unexpected"* ]]; then
        echo "Expected output to NOT contain: $unexpected"
        echo "Actual output: $output"
        return 1
    fi
}

# 断言输出匹配正则表达式
assert_output_matches() {
    local pattern="$1"
    if [[ ! "$output" =~ $pattern ]]; then
        echo "Expected output to match pattern: $pattern"
        echo "Actual output: $output"
        return 1
    fi
}

# 断言文件存在
assert_file_exists() {
    local file="$1"
    if [[ ! -f "$file" ]]; then
        echo "Expected file to exist: $file"
        return 1
    fi
}

# 断言文件不存在
assert_file_not_exists() {
    local file="$1"
    if [[ -f "$file" ]]; then
        echo "Expected file to NOT exist: $file"
        return 1
    fi
}

# 断言目录存在
assert_directory_exists() {
    local dir="$1"
    if [[ ! -d "$dir" ]]; then
        echo "Expected directory to exist: $dir"
        return 1
    fi
}

# 获取脚本版本信息
get_script_version() {
    grep -o 'readonly VERSION="[^"]*"' "$TASKSENTRY_SCRIPT" | cut -d'"' -f2
}

# 检查必需的依赖是否可用
check_test_dependencies() {
    local missing_deps=()
    
    # 检查bats-core
    if ! command -v bats >/dev/null 2>&1; then
        missing_deps+=("bats-core")
    fi
    
    # 检查jq
    if ! command -v jq >/dev/null 2>&1; then
        missing_deps+=("jq")
    fi
    
    # 检查curl
    if ! command -v curl >/dev/null 2>&1; then
        missing_deps+=("curl")
    fi
    
    if [[ ${#missing_deps[@]} -gt 0 ]]; then
        echo "Missing test dependencies: ${missing_deps[*]}"
        return 1
    fi
    
    return 0
}

# 模拟网络请求失败
mock_network_failure() {
    # 创建一个临时的curl脚本，模拟网络失败
    local mock_curl="$TEST_TEMP_DIR/mock_curl"
    cat > "$mock_curl" << 'EOF'
#!/bin/bash
echo "curl: (7) Failed to connect to host" >&2
exit 7
EOF
    chmod +x "$mock_curl"
    export PATH="$TEST_TEMP_DIR:$PATH"
}

# 恢复原始curl
restore_curl() {
    export PATH="${PATH#$TEST_TEMP_DIR:}"
}

# 创建测试日志函数
test_log() {
    echo "[TEST] $*" >&2
}

# BATS测试钩子函数
setup() {
    setup_test_environment
}

teardown() {
    teardown_test_environment
}