#!/bin/bash
# Deploy initial skills to all runtime instances via docker cp
# Usage: ./scripts/deploy-initial-skills.sh

set -euo pipefail

SKILL_SOURCE="/home/ivan/xuan/beaver_project/skills"
DOCKER_NAMES=("app-instance-steven" "app-instance-benson" "app-instance-jayc" "app-instance-officebench")

SKILLS=(
  "outlook-mail"
  "filesystem-operation"
  "terminal-operation"
  "web-operation"
  "utility-tools"
  "skills-admin"
  "cron-scheduler"
  "memory-management"
)

for container in "${DOCKER_NAMES[@]}"; do
  echo "==> Deploying to $container..."

  docker exec "$container" mkdir -p /root/.beaver/workspace/skills/_index

  for skill in "${SKILLS[@]}"; do
    if [ -d "$SKILL_SOURCE/$skill" ]; then
      docker cp "$SKILL_SOURCE/$skill" "$container":/root/.beaver/workspace/skills/
      echo "    + $skill"
    fi
  done

  # Merge index: keep existing entries + add new skills, no duplicates
  docker exec "$container" python3 -c "
import json
from pathlib import Path

idx = Path('/root/.beaver/workspace/skills/_index/published.json')
existing = json.loads(idx.read_text()) if idx.exists() else {'items': []}

new_skills = $(printf '["%s"]' "$(IFS=,; echo "${SKILLS[*]}")" | sed 's/,/", "/g')

seen = set(existing['items'])
for s in new_skills:
    if s not in seen:
        existing['items'].append(s)
        seen.add(s)

idx.write_text(json.dumps(existing, ensure_ascii=False, indent=2) + '\n')
print(f\"Index updated: {len(existing['items'])} skills\")
"

  docker cp "$SKILL_SOURCE/_index/disabled.json" "$container":/root/.beaver/workspace/skills/_index/disabled.json

  echo "    [done]"
done

echo ""
echo "Done! All skills deployed to all instances."
echo "Containers: ${DOCKER_NAMES[*]}"
echo "Skills: ${SKILLS[*]}"
