#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${1:-https://agent.wooo.work}"
MINUTES="${2:-60}"
TRAFFIC_TOKEN="${TRAFFIC_MONITOR_TOKEN:-}"
API_URL="${BASE_URL%/}/api/traffic?minutes=${MINUTES}"
curl_cmd=(curl -sS)

export BASE_URL MINUTES

if [ -n "$TRAFFIC_TOKEN" ]; then
  curl_cmd+=("-H" "x-traffic-token: $TRAFFIC_TOKEN")
fi

PYTHON_INPUT="$(${curl_cmd[@]} "$API_URL")"
export PYTHON_INPUT

python3 - <<'PY'
import json
import os
import sys

raw = os.environ.get("PYTHON_INPUT", "")
try:
    payload = json.loads(raw)
except json.JSONDecodeError:
    print("[A2A External] 無法解析 /api/traffic 回應")
    print(raw[:500])
    sys.exit(1)

print(f"[A2A External] base={os.environ.get('BASE_URL')} minutes={os.environ.get('MINUTES')}")
print(f"total_events={payload.get('total_events')} channel={payload.get('channel_summary', {}).get('external')}")
print(f"claim_success={payload.get('conversion_rates', {}).get('claim_rate')} submit_success={payload.get('conversion_rates', {}).get('submit_rate')}")
print("external_funnel:", payload.get("external_funnel"))
print("top_actors:", payload.get("external_actor_summary"))
print("recent_events:")
for row in (payload.get("recent_external_events") or [])[:8]:
    print(f"  - {row.get('action')} | {row.get('actorId')} | {row.get('surface')} | {row.get('metadata', {}).get('response_status')} | {row.get('reason')}")
PY
