#!/usr/bin/env bash
# 直接對比 OpenCode upstream 與本機 gateway 的原始 JSON/SSE，方便排查空回應
#
# 用法:
#   OPENCODE_TOKEN=sk-xxx ./scripts/debug-opencode-raw.sh

set -u

BASE_URL="${BASE_URL:-http://127.0.0.1:8890}"
OPENCODE_TOKEN="${OPENCODE_TOKEN:-}"
MODEL="${MODEL:-deepseek-v4-flash}"
MESSAGE="${MESSAGE:-Introduce yourself in one sentence.}"

if [[ -z "$OPENCODE_TOKEN" ]]; then
  echo "OPENCODE_TOKEN is required"
  exit 1
fi

require_cmd() {
  command -v "$1" >/dev/null 2>&1 || { echo "missing command: $1"; exit 1; }
}

require_cmd curl
require_cmd jq

payload="$(jq -n \
  --arg model "$MODEL" \
  --arg message "$MESSAGE" \
  '{
    model: $model,
    messages: [{role: "user", content: $message}],
    max_tokens: 2048,
    thinking: {type: "disabled"}
  }')"

echo "=== OpenCode upstream (non-stream) ==="
curl -sS -m 120 -X POST "https://opencode.ai/zen/go/v1/chat/completions" \
  -H "Authorization: Bearer ${OPENCODE_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "$payload" | jq .

echo ""
echo "=== Local gateway (non-stream) ==="
curl -sS -m 120 -X POST "${BASE_URL}/api/v1/ai/chat" \
  -H "Authorization: Bearer ${OPENCODE_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "$(jq -n \
    --arg provider "opencode-go" \
    --arg model "$MODEL" \
    --arg message "$MESSAGE" \
    '{provider:$provider,model:$model,messages:[{role:"user",content:$message}],max_tokens:2048}')" | jq .

echo ""
echo "=== OpenCode upstream (stream, first 20 lines) ==="
curl -sS -N -m 120 -X POST "https://opencode.ai/zen/go/v1/chat/completions" \
  -H "Authorization: Bearer ${OPENCODE_TOKEN}" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d "$(echo "$payload" | jq '.stream=true')" | head -n 20

echo ""
echo "=== Local gateway (stream, first 20 lines) ==="
curl -sS -N -m 120 -X POST "${BASE_URL}/api/v1/ai/chat/stream" \
  -H "Authorization: Bearer ${OPENCODE_TOKEN}" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d "$(jq -n \
    --arg provider "opencode-go" \
    --arg model "$MODEL" \
    --arg message "$MESSAGE" \
    '{provider:$provider,model:$model,messages:[{role:"user",content:$message}],max_tokens:2048}')" | head -n 20