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

SRC_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TARGET_INPUT="${1:-}"

if [ -z "$TARGET_INPUT" ]; then
  echo "Usage: ./scripts/install_into_repo.sh /path/to/target-repo"
  exit 1
fi

mkdir -p "$TARGET_INPUT"
TARGET_ROOT="$(cd "$TARGET_INPUT" && pwd)"

if [ "$TARGET_ROOT" = "$SRC_ROOT" ]; then
  echo "Refusing to install ARNES into its own source repository. Use a different project repo."
  exit 1
fi

if ! git -C "$TARGET_ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "No git repo detected at target. Initializing git repository..."
  git -C "$TARGET_ROOT" init >/dev/null
fi

copy_item() {
  local item="$1"
  if [ -d "$SRC_ROOT/$item" ]; then
    mkdir -p "$TARGET_ROOT/$item"
    cp -R "$SRC_ROOT/$item"/. "$TARGET_ROOT/$item"/
  else
    cp "$SRC_ROOT/$item" "$TARGET_ROOT/$item"
  fi
}

ITEMS=(
  AGENTS.md
  AGENTS.local.md.example
  CHECKPOINTS.md
  HOWTO.md
  HOWTO-FEATURE.md
  README.md
  TEMPLATE.md
  Makefile
  requirements.txt
  backlog
  defaults
  docs
  features
  harness
  platforms
  project
  scripts
  spec
  starter-pack
  work
)

for item in "${ITEMS[@]}"; do
  copy_item "$item"
done

echo "Installed ARNES core into: $TARGET_ROOT"
echo "Next steps:"
echo "  cd $TARGET_ROOT"
echo "  ./scripts/start.sh"
echo "  ./scripts/verify.sh"
