#!/bin/bash
# =============================================================================
# capture_requests.sh — 控制指定 API Key 的请求体捕获开关
# =============================================================================
# 用法:
#   ./capture_requests.sh <key_id> <on|off>
#
# 环境变量（优先级高于脚本内默认值）:
#   BASE_URL     API 服务地址，例如 https://s2a-st.appbym.com
#   ADMIN_KEY    Admin API Key
#
# 示例:
#   BASE_URL=https://example.com ADMIN_KEY=sk-xxx ./capture_requests.sh 123 on
#   ./capture_requests.sh 456 off
# =============================================================================

set -euo pipefail

# ---------- 默认配置（可通过环境变量覆盖）----------
# 自用测试
#DEFAULT_BASE_URL="https://s2a-st.appbym.com"
#DEFAULT_ADMIN_KEY="admin-0c19f7fca7f05050a946c7ded419693f6aa3893221e82b5718663c198b002ace"
# 自用生产
#DEFAULT_BASE_URL="https://codeapi.fcluadecodex.xyz:39443"
#DEFAULT_ADMIN_KEY="admin-50025b892f1b76645ddd6c29853fc1af372098f628ce15352c882648ce7241a1"
# 商用测试
#DEFAULT_BASE_URL="https://s2a-t.appbym.com"
#DEFAULT_ADMIN_KEY="admin-f0781609266d037e64064f11f6db4ce12bb8b7fb78e9fd3e9c7e47a5df6ae748"
# 商用生产
DEFAULT_BASE_URL="https://trafficapi.fcluadecodex.xyz"
DEFAULT_ADMIN_KEY="admin-e75dc89c81a751262a3d814534d739c202f2912d5907007a0a2504434954a0dd"

BASE_URL="${BASE_URL:-$DEFAULT_BASE_URL}"
ADMIN_KEY="${ADMIN_KEY:-$DEFAULT_ADMIN_KEY}"

# ---------- 颜色输出 ----------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

usage() {
    echo "用法: $0 <key_id> <on|off>"
    echo ""
    echo "  key_id   API Key 的数字 ID"
    echo "  on       开启请求体捕获"
    echo "  off      关闭请求体捕获（同时立即清除认证缓存）"
    echo ""
    echo "环境变量:"
    echo "  BASE_URL   API 服务地址（默认: $DEFAULT_BASE_URL）"
    echo "  ADMIN_KEY  Admin API Key（必填）"
    exit 1
}

# ---------- 参数检查 ----------
if [[ $# -ne 2 ]]; then
    echo -e "${RED}错误: 需要 2 个参数${NC}"
    usage
fi

KEY_ID="$1"
ACTION="$2"

# 验证 key_id 是正整数
if ! [[ "$KEY_ID" =~ ^[1-9][0-9]*$ ]]; then
    echo -e "${RED}错误: key_id 必须是正整数，收到: '$KEY_ID'${NC}"
    usage
fi

# 解析 on/off → true/false
case "$ACTION" in
    on|true|1|yes)
        ENABLED="true"
        ACTION_LABEL="开启"
        ;;
    off|false|0|no)
        ENABLED="false"
        ACTION_LABEL="关闭"
        ;;
    *)
        echo -e "${RED}错误: 第二个参数必须是 on 或 off，收到: '$ACTION'${NC}"
        usage
        ;;
esac

# 检查 ADMIN_KEY
if [[ -z "$ADMIN_KEY" ]]; then
    echo -e "${RED}错误: 未设置 ADMIN_KEY${NC}"
    echo "请通过环境变量传入: ADMIN_KEY=sk-xxx $0 $KEY_ID $ACTION"
    exit 1
fi

# ---------- 发送请求 ----------
ENDPOINT="${BASE_URL}/api/v1/admin/api-keys/${KEY_ID}/capture-requests"

echo -e "${YELLOW}▶ ${ACTION_LABEL} API Key #${KEY_ID} 的请求体捕获...${NC}"
echo "  接口: PUT $ENDPOINT"
echo "  参数: enabled=$ENABLED"
echo ""

HTTP_RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X PUT "$ENDPOINT" \
    -H "x-api-key: $ADMIN_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"enabled\": $ENABLED}")

# 分离响应体和状态码
HTTP_BODY=$(echo "$HTTP_RESPONSE" | sed '$d' | tr -d '\r')
HTTP_CODE=$(echo "$HTTP_RESPONSE" | tail -n 1 | tr -d '\r')

# ---------- 结果输出 ----------
echo "HTTP 状态码: $HTTP_CODE"
echo "响应内容:"

# 尝试格式化 JSON（有 jq 就用，没有就原样输出）
if command -v jq &>/dev/null; then
    echo "$HTTP_BODY" | jq .
else
    echo "$HTTP_BODY"
fi

echo ""

if [[ "$HTTP_CODE" == "200" ]]; then
    echo -e "${GREEN}✓ 操作成功：API Key #${KEY_ID} 请求体捕获已${ACTION_LABEL}${NC}"
    if [[ "$ENABLED" == "false" ]]; then
        echo -e "${GREEN}  认证缓存已同步清除，下一条请求立即生效${NC}"
    fi
else
    echo -e "${RED}✗ 操作失败（HTTP $HTTP_CODE）${NC}"
    exit 1
fi
