#!/usr/bin/env bash
#
# Gitea adapter を使う場合に Webhook を登録するスクリプト
#
# 使い方:
#   ./scripts/setup-repo.sh owner/repo
#   ./scripts/setup-repo.sh owner/repo http://orchestrator-host:9877
#
# 環境変数:
#   GITEA_URL              Gitea の URL（デフォルト: config.yaml から取得）
#   GITEA_API_TOKEN        Gitea API トークン（必須）
#   GITEA_WEBHOOK_SECRET   Webhook シークレット（必須）
#   ORCHESTRATOR_URL       Orchestrator の URL（引数でも指定可）
#
set -euo pipefail

REPO="${1:-}"
ORCHESTRATOR_URL="${2:-${ORCHESTRATOR_URL:-}}"

if [ -z "$REPO" ]; then
  echo "Usage: $0 <owner/repo> [orchestrator-url]"
  echo ""
  echo "Examples:"
  echo "  $0 myorg/myrepo"
  echo "  $0 myorg/myrepo http://10.0.0.10:9877"
  echo ""
  echo "Environment variables:"
  echo "  GITEA_API_TOKEN       (required) Gitea API token"
  echo "  GITEA_WEBHOOK_SECRET  (required) Webhook secret"
  echo "  GITEA_URL             Gitea URL (default: from config.yaml)"
  echo "  ORCHESTRATOR_URL      Orchestrator URL (default: http://localhost:9876)"
  exit 1
fi

# config.yaml から GITEA_URL を取得（未設定の場合）
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

if [ -z "${GITEA_URL:-}" ] && [ -f "$PROJECT_DIR/config.yaml" ]; then
  GITEA_URL=$(grep -E '^\s*url:' "$PROJECT_DIR/config.yaml" | head -1 | sed 's/.*url:\s*//' | tr -d '"' | tr -d "'")
fi
GITEA_URL="${GITEA_URL:-https://localhost:3000}"

if [ -z "${GITEA_API_TOKEN:-}" ]; then
  echo "Error: GITEA_API_TOKEN is not set"
  exit 1
fi

if [ -z "${GITEA_WEBHOOK_SECRET:-}" ]; then
  echo "Error: GITEA_WEBHOOK_SECRET is not set"
  exit 1
fi

ORCHESTRATOR_URL="${ORCHESTRATOR_URL:-http://localhost:9876}"
WEBHOOK_URL="${ORCHESTRATOR_URL}/webhook"

echo "Setting up MAESTRO Gitea webhook..."
echo "  Gitea:        $GITEA_URL"
echo "  Repository:   $REPO"
echo "  Webhook URL:  $WEBHOOK_URL"
echo ""

# 既存の webhook を確認
EXISTING=$(curl -sf \
  -H "Authorization: token ${GITEA_API_TOKEN}" \
  "${GITEA_URL}/api/v1/repos/${REPO}/hooks" 2>/dev/null || echo "[]")

# 同じ URL の webhook が既にあるかチェック
if echo "$EXISTING" | python3 -c "
import sys, json
hooks = json.load(sys.stdin)
for h in hooks:
    if h.get('config', {}).get('url', '') == '${WEBHOOK_URL}':
        print(h['id'])
        sys.exit(0)
sys.exit(1)
" 2>/dev/null; then
  echo "Webhook already exists for this URL. Skipping creation."
  exit 0
fi

# Webhook 作成
RESPONSE=$(curl -sf -X POST \
  -H "Authorization: token ${GITEA_API_TOKEN}" \
  -H "Content-Type: application/json" \
  "${GITEA_URL}/api/v1/repos/${REPO}/hooks" \
  -d "{
    \"type\": \"gitea\",
    \"active\": true,
    \"events\": [\"issues\", \"issue_comment\"],
    \"config\": {
      \"url\": \"${WEBHOOK_URL}\",
      \"content_type\": \"json\",
      \"secret\": \"${GITEA_WEBHOOK_SECRET}\"
    }
  }")

HOOK_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])" 2>/dev/null || echo "unknown")
echo "Webhook created (ID: ${HOOK_ID})"

# ヘルスチェック
echo ""
echo -n "Checking orchestrator health... "
if curl -sf "${ORCHESTRATOR_URL}/health" > /dev/null 2>&1; then
  echo "OK"
else
  echo "WARN: orchestrator not reachable at ${ORCHESTRATOR_URL}"
  echo "  Make sure the orchestrator is running and accessible from Gitea."
fi

echo ""
echo "Done! Create an issue on ${GITEA_URL}/${REPO} to test."
echo "If you run in local mode, this script is not needed."
