#!/bin/bash

# 配置
API_URL="http://192.99.37.224:8800/api/v1"
CLIENT_ID="28Single"
API_KEY="dev_token"

# 定义颜色和格式
RED='\033[0;31m'
BOLD='\033[1m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
PURPLE='\033[0;35m'
NC='\033[0m'

# 定义颜色数组
declare -a COLORS=(
    '\033[0;31m'  # 红
    '\033[0;34m'  # 蓝
    '\033[0;35m'  # 紫
    '\033[0;36m'  # 青
    '\033[0;33m'  # 黄
)

# 获取分类颜色
get_category_color() {
    local category="$1"
    local hash=0
    for (( i=0; i<${#category}; i++ )); do
        hash=$((hash + $(printf "%d" "'${category:$i:1}")))
    done
    local color_index=$((hash % ${#COLORS[@]}))
    echo "${COLORS[$color_index]}"
}

# 语法高亮函数
syntax_highlight() {
    local line="$1"
    local keyword="$2"
    # 分离命令和注释部分
    local cmd="${line%#*}"
    local comment=""
    [[ $line == *#* ]] && comment="#${line#*#}"
    
    # 如果有关键词，高亮命令部分
    if [ -n "$keyword" ] && echo "$cmd" | grep -qi "$keyword"; then
        cmd=$(echo "$cmd" | GREP_COLOR="1;31" grep --color=always -i "$keyword")
    fi
    
    # 输出命令和注释
    if [ -n "$comment" ]; then
        if [ -n "$keyword" ] && echo "$comment" | grep -qi "$keyword"; then
            # 高亮注释中的关键词，其余部分保持绿色
            comment=$(echo "$comment" | GREP_COLOR="1;31" grep --color=always -i "$keyword")
            echo -e "${cmd} ${GREEN}${comment}${NC}"
        else
            # 整个注释部分（包括#）都显示为绿色
            echo -e "${cmd} ${GREEN}${comment}${NC}"
        fi
    else
        echo -e "$cmd"
    fi
}

# 格式化输出
format_output() {
    local json_data="$1"
    local keyword="$2"
    local show_id="$3"
    local all_data=""
    local current_data=""
    
    # 收集所有数据并按客户端分类
    while read -r line; do
        client=$(echo "$line" | grep -o '"client_id":"[^"]*"' | cut -d'"' -f4)
        if [ "$client" = "all" ]; then
            all_data+="$line"$'\n'
        elif [ "$client" = "$CLIENT_ID" ]; then
            current_data+="$line"$'\n'
        fi
    done < <(echo "$json_data" | grep -o '{[^}]*}' | sort -t'"' -k4,4)
    
    # 先处理当前客户端
    if [ -n "$current_data" ]; then
        echo -e "${BOLD}${PURPLE}===@$CLIENT_ID===${NC}"
        format_client_data "$current_data" "$keyword" "$show_id"
    fi
    
    # 再处理 all 客户端
    if [ -n "$all_data" ]; then
        [ -n "$current_data" ] && echo ""  # 如果前面有输出则添加空行
        echo -e "${BOLD}${PURPLE}===@all===${NC}"
        format_client_data "$all_data" "$keyword" "$show_id"
    fi
}

# 格式化单个客户端的数据
format_client_data() {
    local client_data="$1"
    local keyword="$2"
    local show_id="$3"
    local current_category=""
    local command_count=0
    
    # 按分类名排序
    echo "$client_data" | sort -t'"' -k6,6 | while read -r line; do
        [ -z "$line" ] && continue
        
        category=$(echo "$line" | grep -o '"category":"[^"]*"' | cut -d'"' -f4)
        command=$(echo "$line" | grep -o '"command":"[^"]*"' | cut -d'"' -f4)
        description=$(echo "$line" | grep -o '"description":"[^"]*"' | cut -d'"' -f4)
        
        # 显示分类标题
        if [ "$current_category" != "$category" ]; then
            [ -n "$current_category" ] && echo ""  # 不是第一个分类才加空行
            current_category="$category"
            category_color=$(get_category_color "$category")
            
            # 高亮匹配的分类名
            if echo "$category" | grep -qi "$keyword"; then
                category=$(echo "$category" | GREP_COLOR="1;31" grep --color=always -i "$keyword")
            fi
            
            echo -e "${BOLD}${category_color}[$category]${NC}"
            command_count=0
        fi
        
        # 显示命令
        command_count=$((command_count + 1))
        id=$(echo "$line" | grep -o '"id":[0-9]*' | cut -d':' -f2)
        echo -n "[${command_count}] "
        if [ "$show_id" = "true" ] && [ -n "$id" ]; then
            echo -n "(ID:${id}) "
        fi
        
        # 构建完整的命令行（包含注释）
        if [ -n "$description" ]; then
            display_line="${command} # ${description}"
        else
            display_line="$command"
        fi
        
        # 使用语法高亮函数处理输出
        syntax_highlight "$display_line" "$keyword"
    done
}

# 搜索命令
search_command() {
    local keyword="$1"
    local show_id="$2"
    if [ -z "$keyword" ] && [ "$1" != "" ]; then
        echo "请提供搜索关键词"
        return 1
    fi

    local response
    response=$(do_request "GET" "/commands/search?keyword=${keyword:-'.'}")
    if [ $? -ne 0 ]; then
        return 1
    fi
    
    if [ -z "$response" ] || [ "$response" = "null" ] || [ "$response" = "[]" ]; then
        echo "未找到匹配的命令"
        return 0
    fi
    
    format_output "$response" "$keyword" "$show_id"
}

# 显示分类列表并返回选择的分类
show_categories() {
    local client_id="$1"
    local categories_data="$2"
    
    # 创建分类数组
    declare -a categories
    if [ -n "$categories_data" ] && [ "$categories_data" != "null" ] && [ "$categories_data" != "[]" ]; then
        while read -r line; do
            category=$(echo "$line" | grep -o '"category":"[^"]*"' | cut -d'"' -f4)
            if [ -n "$category" ]; then
                categories+=("$category")
            fi
        done < <(echo "$categories_data" | grep -o '{[^}]*}')
    fi
    
    # 显示分类列表
    if [ ${#categories[@]} -gt 0 ]; then
        for i in "${!categories[@]}"; do
            category_color=$(get_category_color "${categories[$i]}")
            echo -e "$((i+1))) ${BOLD}${category_color}[${categories[$i]}]${NC}"
        done
        echo "" # 添加空行
    else
        echo "暂无分类"
        echo "" # 添加空行
    fi
    
    # 获取用户选择
    local category=""
    while true; do
        printf "选择分类编号或直接输入新的分类名: "
        read category_choice
        
        # 如果输入为数字，验证是否在有效范围内
        if [[ "$category_choice" =~ ^[0-9]+$ ]]; then
            if [ "$category_choice" -ge 1 ] && [ "$category_choice" -le ${#categories[@]} ]; then
                category="${categories[$((category_choice-1))]}"
                break
            else
                echo "错误：无效的分类编号，请重新输入"
            fi
        else
            # 如果是新分类名，检查是否为空或包含特殊字符
            if [[ -z "$category_choice" ]]; then
                echo "错误：分类名不能为空，请重新输入"
            elif [[ "$category_choice" =~ [\[\]\#] ]]; then
                echo "错误：分类名不能包含 [ ] # 等特殊字符，请重新输入"
            else
                category="$category_choice"
                break
            fi
        fi
    done
    
    echo "$category"
}

# 添加命令
add_command() {
    # 显示选项
    echo "选择命令类型："
    echo "1) 仅当前服务器可用 (@${CLIENT_ID})"
    echo "2) 所有服务器通用 (@all)"
    local tag_choice
    while true; do
        read -p "请选择 (1/2): " tag_choice
        if [[ "$tag_choice" =~ ^[12]$ ]]; then
            break
        else
            echo "错误：请输入1或2"
        fi
    done
    
    # 根据选择设置 client_id
    local client_id
    if [[ $tag_choice == 1 ]]; then
        client_id="$CLIENT_ID"
    else
        client_id="all"
    fi

    # 获取分类数据
    local categories_data=$(do_request "GET" "/commands/search?keyword=.")
    if [ $? -ne 0 ]; then
        return 1
    fi
    
    echo -e "\n现有分类 (@$client_id)："
    declare -a categories
    local category_count=0
    if [ -n "$categories_data" ] && [ "$categories_data" != "null" ] && [ "$categories_data" != "[]" ]; then
        while read -r line; do
            category=$(echo "$line" | grep -o '"category":"[^"]*"' | cut -d'"' -f4)
            client=$(echo "$line" | grep -o '"client_id":"[^"]*"' | cut -d'"' -f4)
            if [ -n "$category" ] && [ "$client" = "$client_id" ]; then
                categories+=("$category")
                category_count=$((category_count + 1))
                category_color=$(get_category_color "$category")
                echo -e "$category_count) ${BOLD}${category_color}[$category]${NC}"
            fi
        done < <(echo "$categories_data" | grep -o '{[^}]*}')
    else
        echo "暂无分类"
    fi
    echo ""

    # 获取分类名
    local category
    while true; do
        read -p "[@$client_id]请输入分类序号或新的分类名称: " category_choice
        
        # 如果输入为数字，验证是否在有效范围内
        if [[ "$category_choice" =~ ^[0-9]+$ ]]; then
            if [ "$category_choice" -ge 1 ] && [ "$category_choice" -le ${#categories[@]} ]; then
                category="${categories[$((category_choice-1))]}"
                break
            else
                echo "错误：无效的分类序号，请重新输入"
            fi
        else
            # 如果是新分类名，检查是否为空或包含特殊字符
            if [[ -z "$category_choice" ]]; then
                echo "错误：分类名不能为空"
            elif [[ "$category_choice" =~ [\[\]\#] ]]; then
                echo "错误：分类名不能包含 [ ] # 等特殊字符"
            else
                category="$category_choice"
                break
            fi
        fi
    done
    
    # 获取命令
    local command
    while true; do
        read -p "[$category]请输入命令: " command
        if [[ -z "$command" ]]; then
            echo "错误：命令不能为空"
        else
            break
        fi
    done
    
    # 获取描述
    read -p "[$category]请输入描述(可选): " description
    
    # 发送添加请求
    local response
    response=$(do_request "POST" "/commands" "{
        \"category\": \"$category\",
        \"command\": \"$command\",
        \"description\": \"$description\"
    }")
    
    if [ $? -eq 0 ]; then
        echo "命令已添加到 [$category] 分类下"
    fi
}

# 编辑命令
edit_command() {
    if [ -z "$1" ]; then
        # 如果没有提供 ID，先显示所有命令
        echo "请使用 -f . 查看所有命令及其 ID"
        echo "然后使用 -edit <ID> 编辑指定命令"
        return 1
    fi

    local id="$1"
    
    # 获取原命令信息
    local cmd_info=$(do_request "GET" "/commands/$id")
    if [ $? -ne 0 ]; then
        return 1
    fi
    
    # 解析并示当前信息
    local current_category=$(echo "$cmd_info" | grep -o '"category":"[^"]*"' | cut -d'"' -f4)
    local current_command=$(echo "$cmd_info" | grep -o '"command":"[^"]*"' | cut -d'"' -f4)
    local current_description=$(echo "$cmd_info" | grep -o '"description":"[^"]*"' | cut -d'"' -f4)
    local current_client=$(echo "$cmd_info" | grep -o '"client_id":"[^"]*"' | cut -d'"' -f4)
    
    echo -e "\n当前命令信息："
    echo -e "客户端: ${BOLD}${PURPLE}@$current_client${NC}"
    echo -e "分类: ${BOLD}$(get_category_color "$current_category")[$current_category]${NC}"
    echo "命令: $current_command"
    echo -e "${GREEN}描述: $current_description${NC}"
    
    # 获取新的输入
    echo -e "\n请输入新的信息（直接回车保持不变）："
    read -p "命令: " new_command
    read -p "描述: " new_description
    
    # 使用原值或新输入的值
    new_command=${new_command:-$current_command}
    new_description=${new_description:-$current_description}
    
    # 发送更新请求
    local response=$(do_request "PUT" "/commands/$id" "{
        \"command\": \"$new_command\",
        \"description\": \"$new_description\"
    }")
    
    if [ $? -eq 0 ]; then
        echo -e "\n命令已更新："
        echo "命令: $new_command"
        echo -e "${GREEN}描述: $new_description${NC}"
    fi
}

# 添加一个通用的 API 请求函数
do_request() {
    local method="$1"
    local endpoint="$2"
    local data="$3"
    local response
    local http_code
    
    # 临时文件存储响应
    local tmp_file=$(mktemp)
    
    # 发送请求并获取 HTTP 状态码
    if [ -n "$data" ]; then
        http_code=$(curl -s -w "%{http_code}" -X "$method" \
            -H "Authorization: Bearer $API_KEY" \
            -H "X-Client-ID: $CLIENT_ID" \
            -H "Content-Type: application/json" \
            -d "$data" \
            "$API_URL$endpoint" -o "$tmp_file")
    else
        http_code=$(curl -s -w "%{http_code}" -X "$method" \
            -H "Authorization: Bearer $API_KEY" \
            -H "X-Client-ID: $CLIENT_ID" \
            "$API_URL$endpoint" -o "$tmp_file")
    fi
    
    # 读取响应内容
    response=$(<"$tmp_file")
    rm -f "$tmp_file"
    
    # 处理错误
    case $http_code in
        200|201) 
            echo "$response"
            return 0
            ;;
        401)
            echo "认证失败：请检查 API Token 是否正确" >&2
            return 1
            ;;
        429)
            echo "请求过于频繁，请稍后再试" >&2
            return 1
            ;;
        *)
            echo "请求失败 (HTTP $http_code): $response" >&2
            return 1
            ;;
    esac
}

# 主命令处理
case "$1" in
    -f)
        search_command "$2" "false"
        ;;
    -all)
        search_command "." "true"
        ;;
    -add)
        add_command
        ;;
    -edit)
        edit_command "$2"
        ;;
    -sync)
        echo "同步功能未实现"
        ;;
    -host)
        echo "当前主机标签: ${CLIENT_ID}"
        ;;
    *)
        echo "使用方法："
        echo "  fastcode -f 关键词     # 搜索命令"
        echo "  fastcode -all         # 显示所有命令"
        echo "  fastcode -add         # 添加命令"
        echo "  fastcode -edit <ID>   # 编辑指定命令"
        echo "  fastcode -sync        # 同步命令（暂未实现）"
        echo "  fastcode -host        # 显示当前主机标签"
        ;;
esac
