#!/bin/bash
set -e

BASE_URL="${1:-http://localhost:3000}"
ADMIN_KEY="${2}"

if [ -z "$ADMIN_KEY" ]; then
    echo "Usage: $0 <base_url> <admin_key>"
    exit 1
fi

echo "=== 渠道定价增强 - 集成测试 ==="

# ---------- 1. 创建渠道定价（含扩展字段） ----------
echo "--- Test 1: Create with extended ratios ---"
RESP=$(curl -s -X POST "$BASE_URL/api/channel-pricing/" \
  -H "Authorization: Bearer $ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model_name": "claude-3-5-sonnet",
    "channel_id": 1,
    "quota_type": 0,
    "model_ratio": 3.0,
    "completion_ratio": 15.0,
    "cache_ratio": 0.5,
    "cache_creation_ratio": 0.625,
    "image_ratio": 1.5,
    "audio_ratio": 2.0,
    "audio_completion_ratio": 1.8
  }')
echo "$RESP" | python3 -m json.tool

CACHE_RATIO=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['cache_ratio'])")
if [ "$CACHE_RATIO" = "0.5" ]; then
    echo "  [PASS] cache_ratio = 0.5"
else
    echo "  [FAIL] cache_ratio expected 0.5, got $CACHE_RATIO"
fi

# ---------- 2. 查询渠道定价（验证新字段返回） ----------
echo "--- Test 2: Query and verify extended fields ---"
RESP=$(curl -s "$BASE_URL/api/channel-pricing/model/claude-3-5-sonnet" \
  -H "Authorization: Bearer $ADMIN_KEY")
echo "$RESP" | python3 -m json.tool

# ---------- 3. 更新渠道定价（修改扩展字段） ----------
echo "--- Test 3: Update extended ratios ---"
RESP=$(curl -s -X POST "$BASE_URL/api/channel-pricing/" \
  -H "Authorization: Bearer $ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model_name": "claude-3-5-sonnet",
    "channel_id": 1,
    "quota_type": 0,
    "model_ratio": 3.0,
    "completion_ratio": 15.0,
    "cache_ratio": 0.8,
    "cache_creation_ratio": 0.0
  }')
echo "$RESP" | python3 -m json.tool

# ---------- 4. 验证回退：未设置的字段为 0 ----------
echo "--- Test 4: Verify unset fields = 0 ---"
CACHE_CREATION=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['cache_creation_ratio'])")
if [ "$CACHE_CREATION" = "0.0" ]; then
    echo "  [PASS] cache_creation_ratio = 0 (unset)"
else
    echo "  [FAIL] cache_creation_ratio expected 0.0, got $CACHE_CREATION"
fi

# ---------- 5. 负值校验 ----------
echo "--- Test 5: Reject negative values ---"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$BASE_URL/api/channel-pricing/" \
  -H "Authorization: Bearer $ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model_name": "claude-3-5-sonnet",
    "channel_id": 1,
    "quota_type": 0,
    "model_ratio": 3.0,
    "cache_ratio": -1.0
  }')
if [ "$HTTP_CODE" = "400" ] || [ "$HTTP_CODE" = "422" ]; then
    echo "  [PASS] negative value rejected with HTTP $HTTP_CODE"
else
    echo "  [FAIL] expected 400/422, got HTTP $HTTP_CODE"
fi

# ---------- 6. 用户端查询（带渠道信息 + CASE WHEN 回退） ----------
echo "--- Test 6: User-facing query with global fallback ---"
RESP=$(curl -s "$BASE_URL/api/channel-pricing/model/claude-3-5-sonnet" \
  -H "Authorization: Bearer $ADMIN_KEY")
echo "$RESP" | python3 -c "
import sys, json
data = json.load(sys.stdin)
for item in data.get('data', []):
    ch = item.get('channel_id', '?')
    cr = item.get('cache_ratio', 'N/A')
    ccr = item.get('cache_creation_ratio', 'N/A')
    ir = item.get('image_ratio', 'N/A')
    print(f'  channel={ch} cache_ratio={cr} cache_creation_ratio={ccr} image_ratio={ir}')
"

# ---------- 7. 删除 + 验证缓存清除 ----------
echo "--- Test 7: Delete and verify cache cleared ---"
ID=$(curl -s "$BASE_URL/api/channel-pricing/model/claude-3-5-sonnet" \
  -H "Authorization: Bearer $ADMIN_KEY" | \
  python3 -c "import sys,json; items=json.load(sys.stdin).get('data',[]); print(items[0]['id'] if items else '')")
if [ -n "$ID" ]; then
    curl -s -X DELETE "$BASE_URL/api/channel-pricing/$ID" \
      -H "Authorization: Bearer $ADMIN_KEY"
    echo "  Deleted pricing id=$ID"

    RESP=$(curl -s "$BASE_URL/api/channel-pricing/model/claude-3-5-sonnet" \
      -H "Authorization: Bearer $ADMIN_KEY")
    COUNT=$(echo "$RESP" | python3 -c "import sys,json; print(len(json.load(sys.stdin).get('data',[])))")
    echo "  Remaining pricings for claude-3-5-sonnet: $COUNT"
else
    echo "  [SKIP] No pricing to delete"
fi

echo "=== 集成测试完成 ==="
