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

repository_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repository_root"

pnpm n8n:build
pnpm n8n:validate

if ! docker compose ps --status running --services | grep -qx n8n; then
  echo "n8n is not running. Start the stack with: docker compose up -d" >&2
  exit 1
fi

api_key="${N8N_API_KEY:-$(docker compose exec -T n8n sh -c 'printf %s "${N8N_API_KEY:-}"')}"
if [ -z "$api_key" ]; then
  echo "N8N_API_KEY is empty. Create an owner and API key in n8n, save it in .env, then recreate n8n." >&2
  exit 1
fi

docker compose exec -T n8n sh -c 'command -v envsubst >/dev/null' || {
  echo "envsubst is missing from the n8n image; rebuild with: docker compose build n8n" >&2
  exit 1
}

if ! docker compose exec -T n8n sh -ec '
  rendered="$(mktemp /tmp/smart-cod-credentials.XXXXXX)"
  trap '\''rm -f "$rendered"'\'' EXIT
  umask 077
  envsubst < /credential-templates/credentials.json > "$rendered"
  node -e '\''JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))'\'' "$rendered"
  n8n import:credentials --input="$rendered" --include=id,name,type,data
'; then
  cat >&2 <<'EOF'
Credential import failed. In n8n, open Credentials and create these entries manually, then select them on the matching nodes:
  COD Internal API Bearer, COD Telegram Bot, COD SMTP, COD OpenAI,
  COD Public Webhook Key, and COD Dashboard Event Token.
Workflow import will continue so the canvas can still be inspected and repaired in the UI.
EOF
fi

docker compose exec -T n8n n8n import:workflow --separate --input=/workflows

mapfile -t workflow_ids < <(
  node -e '
    const fs = require("node:fs");
    const path = require("node:path");
    for (const filename of fs.readdirSync("n8n/dist").filter((name) => name.endsWith(".workflow.json")).sort()) {
      const workflow = JSON.parse(fs.readFileSync(path.join("n8n/dist", filename), "utf8"));
      process.stdout.write(`${workflow.id}\n`);
    }
  '
)

pending_ids=("${workflow_ids[@]}")
for ((pass = 1; pass <= ${#workflow_ids[@]} && ${#pending_ids[@]} > 0; pass += 1)); do
  next_pending=()
  activated_this_pass=0
  for workflow_id in "${pending_ids[@]}"; do
    if docker compose exec -T -e WORKFLOW_ID="$workflow_id" -e N8N_API_KEY="$api_key" n8n node -e '
      const id = process.env.WORKFLOW_ID;
      const key = process.env.N8N_API_KEY;
      fetch(`http://127.0.0.1:5678/api/v1/workflows/${encodeURIComponent(id)}/activate`, {
        method: "POST",
        headers: { "X-N8N-API-KEY": key },
      }).then(async (response) => {
        if (!response.ok) throw new Error(`activation of ${id} returned HTTP ${response.status}: ${await response.text()}`);
        process.stdout.write(`Activated ${id}\n`);
      }).catch((error) => { console.error(error.message); process.exit(1); });
    ' 2>/dev/null; then
      activated_this_pass=$((activated_this_pass + 1))
    else
      next_pending+=("$workflow_id")
    fi
  done
  pending_ids=("${next_pending[@]}")
  if [ "$activated_this_pass" -eq 0 ] && [ "${#pending_ids[@]}" -gt 0 ]; then
    echo "Unable to activate workflows after resolving sub-workflow dependencies: ${pending_ids[*]}" >&2
    exit 1
  fi
done

echo "Imported and activated ${#workflow_ids[@]} workflows."
