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

PORTAL_URL="${HABIFY_ENGLISH_URL:-https://english.dev.habifyhub.com}"
TARGET="all"

while [ $# -gt 0 ]; do
  case "$1" in
    --target)
      TARGET="${2:-all}"
      shift 2
      ;;
    --api-url)
      PORTAL_URL="${2:-https://english.dev.habifyhub.com}"
      shift 2
      ;;
    *)
      shift
      ;;
  esac
done

PORTAL_URL="${PORTAL_URL%/}"

install_into() {
  local root_dir="$1"
  mkdir -p "${root_dir}/habify-english" \
           "${root_dir}/habify-english-author" \
           "${root_dir}/habify-english-help-spec" \
           "${root_dir}/habify-english-pedagogy"

  curl -fsSL "${PORTAL_URL}/skill.md" -o "${root_dir}/habify-english/SKILL.md"
  curl -fsSL "${PORTAL_URL}/skills/author/SKILL.md" -o "${root_dir}/habify-english-author/SKILL.md"
  curl -fsSL "${PORTAL_URL}/skills/help-spec/SKILL.md" -o "${root_dir}/habify-english-help-spec/SKILL.md"
  curl -fsSL "${PORTAL_URL}/skills/pedagogy/SKILL.md" -o "${root_dir}/habify-english-pedagogy/SKILL.md"

  echo "✓ Installed Habify English skills -> ${root_dir}"
}

case "${TARGET}" in
  claude)
    install_into "${HOME}/.claude/skills"
    ;;
  codex)
    install_into "${HOME}/.codex/skills"
    ;;
  gemini)
    install_into "${HOME}/.gemini/skills"
    ;;
  all|*)
    install_into "${HOME}/.claude/skills"
    install_into "${HOME}/.codex/skills"
    install_into "${HOME}/.gemini/skills"
    ;;
esac

echo ""
echo "Next steps:"
echo "  1. Generate a scoped token (eng_agt_...) in Admin Studio or Center Studio."
echo "  2. Export credentials:"
echo "       export HABIFY_ENGLISH_URL="${PORTAL_URL}""
echo "       export HABIFY_ENGLISH_AGENT_TOKEN="eng_agt_...""
echo "  3. Fetch live spec & start authoring:"
echo "       curl -fsS -H "Authorization: Bearer \$HABIFY_ENGLISH_AGENT_TOKEN" "${PORTAL_URL}/api/v1/agent/spec""
