#!/bin/bash
# xFrame.ai skill suite installer
#
# Usage:
#   install-skills.sh [--check] [--aliases] [--help]
#
#   --check     Compare the installed suite version to latest and exit
#   --aliases   Install command aliases for each skill CLI
#   -h, --help  Show this help

REPO="https://github.com/exergy-connect/xFrame.ai.git"
SKILLS=(
  "skills/xframe-model"
  "skills/xframe-consolidate"
  "skills/xframe-present"
  "skills/xform-author"
  "skills/xform-run"
)
TARGET=".cursor/skills"
VERSION_URL="https://exergy-connect.github.io/xFrame.ai/latest"
ACTION_CLIS=(
  "actions/consolidate|xframe-consolidate|consolidate.min.js"
  "actions/present|xframe-present|present.min.js"
  "actions/xform|xform-run|xform.min.js"
)
ALIAS_BEGIN="# BEGIN xFrame.ai skill aliases"
ALIAS_END="# END xFrame.ai skill aliases"

usage() {
  cat <<'EOF'
Usage: install-skills.sh [--check] [--aliases]

  --check     Compare the installed suite version to latest and exit
  --aliases   Install command aliases for each skill CLI
  -h, --help  Show this help

Skills install into .cursor/skills/ (run from a project root that has .cursor/).
--aliases writes PATH wrappers and bash aliases for each skill that ships a CLI.
Set XFRAME_SKILLS_ROOT to override the absolute skills directory.
EOF
}

DO_CHECK=0
DO_ALIASES=0

for arg in "$@"; do
  case "$arg" in
    --check) DO_CHECK=1 ;;
    --aliases) DO_ALIASES=1 ;;
    -h|--help) usage; exit 0 ;;
    *)
      echo "Unknown option: $arg" >&2
      usage >&2
      exit 1
      ;;
  esac
done

_install_file() {
  local dest=$1 mode=${2:-644}
  local tmp dir
  tmp=$(mktemp)
  cat >"$tmp"
  dir=$(dirname "$dest")
  mkdir -p "$dir"
  install -m "$mode" "$tmp" "$dest"
  rm -f "$tmp"
}

_upsert_marked_block() {
  local dest=$1
  local block=$2
  local tmp
  tmp=$(mktemp)
  if [ -f "$dest" ]; then
    awk -v b="$ALIAS_BEGIN" -v e="$ALIAS_END" '
      $0 == b { skip = 1; next }
      $0 == e { skip = 0; next }
      !skip { print }
    ' "$dest" >"$tmp"
  else
    : >"$tmp"
  fi
  # Drop trailing blank lines so reruns do not accumulate separators
  awk 'NF{n=NR} {a[NR]=$0} END{for(i=1;i<=n;i++) print a[i]}' "$tmp" >"${tmp}.trim"
  mv "${tmp}.trim" "$tmp"
  printf '\n%s\n%s\n%s\n' "$ALIAS_BEGIN" "$block" "$ALIAS_END" >>"$tmp"
  _install_file "$dest" 644 <"$tmp"
  rm -f "$tmp"
}

_skills_root() {
  local root candidate
  for candidate in "${XFRAME_SKILLS_ROOT:-}" "${INSTALL_SKILLS_ROOT:-}"; do
    if [ -n "$candidate" ] && [ -d "$candidate" ]; then
      (cd "$candidate" && pwd)
      return 0
    fi
  done
  if [ -d "$TARGET" ]; then
    (cd "$TARGET" && pwd)
    return 0
  fi
  return 1
}

_skill_script() {
  local skills_root=$1 skill_name=$2 bundle=$3
  printf '%s/%s/scripts/%s' "$skills_root" "$skill_name" "$bundle"
}

_alias_names() {
  local skill_name=$1 bundle=$2
  local short="${bundle%.min.js}"
  printf '%s\n' "$skill_name"
  case "$short" in
    xform*|xframe*)
      if [ "$short" != "$skill_name" ]; then
        printf '%s\n' "$short"
      fi
      ;;
  esac
}

_alias_block() {
  local skills_root=$1 bindir=$2
  local spec skill_name bundle name script
  if [ -n "$bindir" ]; then
    printf 'case ":$PATH:" in *:"%s":*) ;; *) PATH="%s:$PATH" ;; esac\n' "$bindir" "$bindir"
  fi
  cat <<'EOF'
if [ -n "${BASH_VERSION:-}" ]; then
EOF
  for spec in "${ACTION_CLIS[@]}"; do
    IFS='|' read -r _ skill_name bundle <<<"$spec"
    script=$(_skill_script "$skills_root" "$skill_name" "$bundle")
    while IFS= read -r name; do
      printf "  alias %s='node %q'\n" "$name" "$script"
    done < <(_alias_names "$skill_name" "$bundle")
  done
  printf 'fi\n'
}

install_aliases() {
  local bindir alias_file skills_root spec skill_name bundle name names script

  if ! skills_root=$(_skills_root); then
    echo "Cannot install aliases: skills directory not found. Install skills first or set XFRAME_SKILLS_ROOT." >&2
    return 1
  fi

  if [ -n "${XFRAME_ALIAS_BIN:-}" ]; then
    bindir="$XFRAME_ALIAS_BIN"
    alias_file="${XFRAME_ALIAS_FILE:-$HOME/.bash_aliases}"
  elif [ "$(id -u)" -eq 0 ]; then
    bindir=/usr/local/bin
    alias_file=/etc/profile.d/xframe-ai-skills.sh
  else
    bindir="${HOME}/.local/bin"
    alias_file="${HOME}/.bash_aliases"
  fi
  mkdir -p "$bindir"

  for spec in "${ACTION_CLIS[@]}"; do
    IFS='|' read -r _ skill_name bundle <<<"$spec"
    script=$(_skill_script "$skills_root" "$skill_name" "$bundle")
    if [ ! -f "$script" ]; then
      echo "Skill CLI missing: $script" >&2
      return 1
    fi
    names=""
    while IFS= read -r name; do
      _install_file "$bindir/$name" 755 <<EOF
#!/bin/sh
exec node "$script" "\$@"
EOF
      names="${names:+$names, }$name"
    done < <(_alias_names "$skill_name" "$bundle")
    echo "Alias installed: $names -> $script"
  done

  if [ "$alias_file" = "/etc/profile.d/xframe-ai-skills.sh" ]; then
    {
      echo "# Generated by xFrame.ai install-skills.sh — do not edit"
      _alias_block "$skills_root" ""
    } >"${TMPDIR:-/tmp}/xframe-ai-skills.sh"
    _install_file "$alias_file" 644 <"${TMPDIR:-/tmp}/xframe-ai-skills.sh"
    rm -f "${TMPDIR:-/tmp}/xframe-ai-skills.sh"
  else
    if [ "$bindir" = "${HOME}/.local/bin" ] || [ -n "${XFRAME_ALIAS_BIN:-}" ]; then
      _upsert_marked_block "$alias_file" "$(_alias_block "$skills_root" "$bindir")"
    else
      _upsert_marked_block "$alias_file" "$(_alias_block "$skills_root" "")"
    fi
  fi
}

if [ "$DO_CHECK" -eq 1 ]; then
  LATEST=$(curl -fsSL "$VERSION_URL")
  LOCAL=$(cat "$TARGET/.xframe-latest" 2>/dev/null || echo "not installed")
  echo "Installed: $LOCAL — Latest: $LATEST"
  [ "$LOCAL" = "$LATEST" ] && echo "Up to date." || echo "Update available. Re-run without --check to install."
  exit 0
fi

if [ ! -d ".cursor" ]; then
  if [ "$DO_ALIASES" -eq 1 ]; then
    install_aliases || exit 1
    echo "Command aliases installed."
    exit 0
  fi
  echo "No .cursor directory found. Run this from your project root."
  exit 1
fi

TMP=$(mktemp -d)
git clone --filter=blob:none --sparse "$REPO" "$TMP"
cd "$TMP"

SPARSE=("${SKILLS[@]}")
for spec in "${ACTION_CLIS[@]}"; do
  SPARSE+=("${spec%%|*}")
done
git sparse-checkout set "${SPARSE[@]}"

mkdir -p "$OLDPWD/$TARGET"
for SKILL in "${SKILLS[@]}"; do
  SKILL_NAME=$(basename "$SKILL")
  rm -rf "$OLDPWD/$TARGET/$SKILL_NAME"
  cp -r "$SKILL" "$OLDPWD/$TARGET/$SKILL_NAME"
  echo "Installed: $SKILL_NAME"
done

for spec in "${ACTION_CLIS[@]}"; do
  IFS='|' read -r action_dir skill_name bundle <<< "$spec"
  dest="$OLDPWD/$TARGET/$skill_name"
  if [ -f "$dest/install.sh" ]; then
    bash "$dest/install.sh" "$TMP/$action_dir" "$dest"
    continue
  fi
  src="$TMP/$action_dir/$bundle"
  if [ ! -f "$src" ]; then
    echo "Action bundle missing at $action_dir/$bundle" >&2
    exit 1
  fi
  scripts="$dest/scripts"
  mkdir -p "$scripts"
  cp "$src" "$scripts/$bundle"
  if [ -f "$TMP/$action_dir/package.json" ]; then
    cp "$TMP/$action_dir/package.json" "$scripts/package.json"
  fi
  echo "Installed: $skill_name CLI from $action_dir"
done

# Record installed version
SUITE_VERSION=$(curl -fsSL "$VERSION_URL")
echo "$SUITE_VERSION" > "$OLDPWD/$TARGET/.xframe-latest"

rm -rf "$TMP"
echo "xFrame.ai suite v$SUITE_VERSION installed."

if [ "$DO_ALIASES" -eq 1 ]; then
  cd "$OLDPWD"
  INSTALL_SKILLS_ROOT="$(cd "$OLDPWD/$TARGET" && pwd)"
  install_aliases || exit 1
fi
