#!/usr/bin/env bash

# 脚本名称
SCRIPT_NAME="wgr.sh"

# 定义目录变量
JS_DIR="./js"
LOG_DIR="./log"
DB_DIR="./db"
MAIN_LOG_FILE="${LOG_DIR}/wgr.log"

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

# 全局变量
BATCH_NUMBER=""
BATCH_LOG_FILE=""
declare -a AVAILABLE_SCRIPTS

# --- 核心函数：日志记录 ---
log_message() {
    local level=$1
    local message=$2
    local color=$NC

    case "$level" in
        "INFO") color=$BLUE ;;
        "SUCCESS") color=$GREEN ;;
        "WARNING") color=$YELLOW ;;
        "ERROR") color=$RED ;;
        "ROLLBACK") color=$RED ;;
    esac

    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local log_line="[$timestamp] [$level] $message"

    mkdir -p "$LOG_DIR"
    echo "$log_line" >> "$MAIN_LOG_FILE"
    echo -e "${color}[$level]${NC} $message"
}

# --- 基础环境函数 ---

create_base_dirs() {
    log_message "INFO" "正在检查并创建基础目录..."
    for dir in "$JS_DIR" "$LOG_DIR" "$DB_DIR"; do
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir"
            log_message "SUCCESS" "目录已创建: $dir"
        else
            log_message "INFO" "目录已存在: $dir"
        fi
    done
}

set_js_permissions() {
    log_message "INFO" "正在检查并设置 $JS_DIR 目录下脚本的执行权限..."
    shopt -s nullglob
    for file in "$JS_DIR"/*.sh; do
        chmod +x "$file"
    done
    shopt -u nullglob
}

get_batch_number() {
    while true; do
        echo "----------------------------------------"
        read -p "请输入此次执行的批次号 (直接回车使用当前时间，输入 exit 退出): " batch_input

        log_message "INFO" "用户输入批次号: ${batch_input:-[自动生成]}"

        if [[ "$batch_input" == "exit" ]]; then
            log_message "INFO" "用户选择退出，脚本执行结束。"
            exit 0
        elif [[ -z "$batch_input" ]]; then
            BATCH_NUMBER=$(date +%Y%m%d%H%M%S)
            log_message "INFO" "未输入批次号，已自动生成: $BATCH_NUMBER"
            break
        else
            BATCH_NUMBER="$batch_input"
            log_message "INFO" "使用自定义批次号: $BATCH_NUMBER"
            break
        fi
    done
}

create_batch_log() {
    local dolog_dir="${LOG_DIR}/dolog"
    BATCH_LOG_FILE="${dolog_dir}/${BATCH_NUMBER}.txt"

    log_message "INFO" "正在准备批次日志文件..."

    mkdir -p "$dolog_dir"

    if [ ! -f "$BATCH_LOG_FILE" ]; then
        touch "$BATCH_LOG_FILE"
        log_message "SUCCESS" "批次日志文件已创建: $BATCH_LOG_FILE"
    else
        log_message "INFO" "批次日志文件已存在。"
    fi
}

# --- 核心逻辑：扫描与菜单 ---

scan_and_show_menu() {
    local script_files=()
    AVAILABLE_SCRIPTS=()

    shopt -s nullglob
    for file in "$JS_DIR"/*.sh; do
        local filename=$(basename "$file")
        if [[ "$filename" =~ ^[0-9]+.*\.sh$ ]]; then
            script_files+=("$filename")
        fi
    done
    shopt -u nullglob

    if [ ${#script_files[@]} -eq 0 ]; then
        log_message "WARNING" "在 $JS_DIR 目录下没有找到任何以数字开头的 .sh 脚本文件。"
        exit 0
    fi

    IFS=$'\n' sorted_files=($(sort <<<"${script_files[*]}"))
    unset IFS

    echo "----------------------------------------"
    log_message "INFO" "发现以下任务脚本，请选择要执行的选项："
    echo "----------------------------------------"

    local index=1
    for filename in "${sorted_files[@]}"; do
        local description=$(echo "$filename" | sed -E 's/^[0-9]+[_\-]?//; s/\.sh$//')

        local record=$(grep "^$filename " "$BATCH_LOG_FILE" 2>/dev/null)
        local status_mark=""

        if [[ -n "$record" ]]; then
            local count=$(echo "$record" | awk '{print $2}')
            local last_time=$(echo "$record" | cut -d' ' -f3-)

            if [ "$count" -gt 0 ]; then
                status_mark="${GREEN} ✔ (成功 ${count} 次, 最后: ${last_time})${NC}"
            else
                status_mark="${RED} ✘ (失败 ${count} 次, 最后: ${last_time})${NC}"
            fi
        fi

        AVAILABLE_SCRIPTS[$index]="$filename"
        printf "  [%d] %s%s\n" "$index" "$description" "$status_mark"
        ((index++))
    done
    echo "----------------------------------------"
}

execute_script() {
    local script_name=$1
    local script_path="$JS_DIR/$script_name"

    log_message "INFO" "开始执行脚本: $script_name"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 开始执行: $script_name" >> "$BATCH_LOG_FILE"

    # 直接运行脚本，让子脚本的颜色代码能被终端正确解析
    # 同时通过管道将输出追加到日志文件（注意：这样可能会导致日志文件中包含颜色代码，但在终端显示正常）
    # 为了保持日志文件纯净，我们只记录标准输出，不记录颜色代码（子脚本内部已处理写入文件）
    if bash "$script_path"; then
        log_message "SUCCESS" "脚本 $script_name 执行成功！"
        update_script_record "$script_name" 1
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] 成功完成: $script_name" >> "$BATCH_LOG_FILE"
    else
        log_message "ERROR" "脚本 $script_name 执行失败！"
        log_message "ROLLBACK" "正在尝试执行回滚操作..."

        update_script_record "$script_name" -1
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] 执行失败并已回滚: $script_name" >> "$BATCH_LOG_FILE"
    fi
}

update_script_record() {
    local script_name=$1
    local count_change=$2
    local temp_file=$(mktemp)
    local record_found=false
    local current_time=$(date '+%Y-%m-%d %H:%M:%S')
    local new_count=$count_change

    while IFS= read -r line || [[ -n "$line" ]]; do
        if [[ "$line" == "$script_name "* ]]; then
            local old_count=$(echo "$line" | awk '{print $2}')
            new_count=$((old_count + count_change))
            echo "$script_name $new_count $current_time" >> "$temp_file"
            record_found=true
        else
            echo "$line" >> "$temp_file"
        fi
    done < "$BATCH_LOG_FILE"

    if [ "$record_found" = false ]; then
        echo "$script_name $new_count $current_time" >> "$temp_file"
    fi

    mv "$temp_file" "$BATCH_LOG_FILE"
}

# --- 主程序 ---
main() {
    mkdir -p "$LOG_DIR"
    echo "========================================" >> "$MAIN_LOG_FILE"
    log_message "INFO" "脚本 $SCRIPT_NAME 启动"

    create_base_dirs
    set_js_permissions
    get_batch_number
    create_batch_log

    while true; do
        scan_and_show_menu

        read -p "请输入选项数字执行脚本，或输入 exit 退出: " user_choice

        log_message "INFO" "用户输入选项: $user_choice"

        if [[ "$user_choice" == "exit" ]]; then
            log_message "INFO" "用户选择退出，脚本执行结束。"
            break
        elif [[ "$user_choice" =~ ^[0-9]+$ ]]; then
            if [[ -n "${AVAILABLE_SCRIPTS[$user_choice]}" ]]; then
                local selected_script="${AVAILABLE_SCRIPTS[$user_choice]}"
                execute_script "$selected_script"
                echo "----------------------------------------"
            else
                log_message "ERROR" "无效的选项。"
            fi
        else
            log_message "ERROR" "无效输入。"
        fi
    done
}

main

