#!/bin/bash
# n8n REST API로 워크플로우 업데이트
# 사용법: ./deploy_workflows.sh [--activate]
# 필요: N8N_API_KEY 환경변수 또는 .env 파일
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
N8N_URL="${N8N_URL:-http://localhost:5678}"
WORKFLOW_DIR="$SCRIPT_DIR/n8n/workflows"

# .env에서 API 키 로드
if [ -z "${N8N_API_KEY:-}" ] && [ -f "$SCRIPT_DIR/.env" ]; then
    N8N_API_KEY=$(grep '^N8N_API_KEY=' "$SCRIPT_DIR/.env" | cut -d= -f2-)
fi
if [ -z "${N8N_API_KEY:-}" ]; then
    echo "ERROR: N8N_API_KEY not set. Set it in .env or as environment variable."
    exit 1
fi

AUTH_HEADER="X-N8N-API-KEY: $N8N_API_KEY"
ACTIVATE="${1:-}"

# 워크플로우 이름 → ID 매핑 (n8n API에서 조회)
get_workflow_id() {
    local name="$1"
    curl -s -H "$AUTH_HEADER" "$N8N_URL/api/v1/workflows?limit=100" \
        | python3 -c "
import sys, json
data = json.loads(sys.stdin.read())
for wf in data.get('data', []):
    if wf['name'] == '$name':
        print(wf['id'])
        break
"
}

deploy_workflow() {
    local file="$1"
    local name
    name=$(python3 -c "import json; print(json.load(open('$file'))['name'])")
    local wf_id
    wf_id=$(get_workflow_id "$name")

    if [ -z "$wf_id" ]; then
        echo "  Creating new workflow: $name"
        wf_id=$(curl -s -X POST "$N8N_URL/api/v1/workflows" \
            -H "$AUTH_HEADER" \
            -H "Content-Type: application/json" \
            -d @"$file" \
            | python3 -c "import sys, json; print(json.loads(sys.stdin.read())['id'])")
        echo "  Created: $wf_id"
    else
        echo "  Updating workflow: $name (id=$wf_id)"
        local http_code
        http_code=$(curl -s -o /dev/null -w '%{http_code}' -X PUT \
            "$N8N_URL/api/v1/workflows/$wf_id" \
            -H "$AUTH_HEADER" \
            -H "Content-Type: application/json" \
            -d @"$file")
        if [ "$http_code" -ge 400 ]; then
            echo "  FAILED (HTTP $http_code)"
            return 1
        fi
        echo "  Updated (HTTP $http_code)"
    fi

    if [ "$ACTIVATE" = "--activate" ]; then
        curl -s -X POST "$N8N_URL/api/v1/workflows/$wf_id/activate" \
            -H "$AUTH_HEADER" > /dev/null
        echo "  Activated"
    fi
}

echo "=== n8n Workflow Deploy ==="
echo "Target: $N8N_URL"
echo ""

for file in "$WORKFLOW_DIR"/*.json; do
    echo "[$(basename "$file")]"
    deploy_workflow "$file"
    echo ""
done

echo "Done."
