#!/usr/bin/env bash
# Bundle a folder of files into the JSON body shape expected by
# POST /v1/skills on the Agento public API.
#
# Usage: bundle-skill.sh <skill-folder> <name> <description> <version>
# Example:
#   ./bundle-skill.sh ./my-skill my-trello-helper "Manage Trello via REST." 1.0.0 \
#     | curl -s https://api.agento.host/v1/skills \
#         -H "X-Api-Key: $AGENTO_API_KEY" \
#         -H "Content-Type: application/json" \
#         -d @-
#
# Requires: jq, find, sed.

set -euo pipefail

DIR="${1:-.}"
NAME="${2:?name required (positional arg 2)}"
DESCRIPTION="${3:?description required (positional arg 3)}"
VERSION="${4:?version required (positional arg 4)}"

cd "$DIR"
[ -f SKILL.md ] || { echo "SKILL.md not found in $DIR" >&2; exit 1; }

# Walk the directory, skip dotfiles, build the {path: content} map with jq.
files_json=$(
  printf '{'
  first=1
  while IFS= read -r path; do
    [ "$first" -eq 1 ] || printf ','
    first=0
    printf '%s:%s' "$(printf '%s' "$path" | jq -R)" "$(jq -Rs . < "$path")"
  done < <(find . -type f -not -path '*/.*' | sed 's|^\./||' | sort)
  printf '}'
)

jq -n \
  --arg name "$NAME" \
  --arg description "$DESCRIPTION" \
  --arg version "$VERSION" \
  --argjson files "$files_json" \
  '{ name: $name, description: $description, version: $version, files: $files }'
