#!/usr/bin/env bash

# Install project-owned public skills and sync public project defaults into a
# deduplicated Codex long-term-memory update.
# Usage: bash scripts/install_skills_to_codex.sh [--dry-run]

set -euo pipefail

usage() {
  printf 'Usage: %s [--dry-run]\n' "${0##*/}"
}

dry_run=false
case "${1:-}" in
  '') ;;
  --dry-run) dry_run=true ;;
  -h|--help) usage; exit 0 ;;
  *) usage >&2; exit 2 ;;
esac

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
skill_source="$repo_root/skills"
codex_home="${CODEX_HOME:-$HOME/.codex}"
skill_destination_root="$codex_home/skills"
installed=0

if [[ ! -d "$skill_source" ]]; then
  printf 'ERROR: skill source directory is missing: %s\n' "$skill_source" >&2
  exit 1
fi

while IFS= read -r -d '' skill_file; do
  source_dir="$(dirname "$skill_file")"
  skill_name="$(basename "$source_dir")"
  destination_dir="$skill_destination_root/$skill_name"

  if [[ "$dry_run" == true ]]; then
    printf 'WOULD_INSTALL %s -> %s\n' "$source_dir" "$destination_dir"
  else
    mkdir -p "$destination_dir"
    cp -R "$source_dir/." "$destination_dir/"
    printf 'INSTALLED %s -> %s\n' "$skill_name" "$destination_dir"
  fi
  installed=$((installed + 1))
done < <(find "$skill_source" -mindepth 2 -maxdepth 2 -type f -name SKILL.md -print0 | sort -z)

if (( installed == 0 )); then
  printf 'ERROR: no project skills found under %s\n' "$skill_source" >&2
  exit 1
fi

if [[ "$dry_run" == true ]]; then
  printf 'DRY_RUN_OK skills=%d source=%s destination=%s\n' "$installed" "$skill_source" "$skill_destination_root"
  bash "$repo_root/scripts/sync_project_memory_to_codex.sh" --dry-run
else
  printf 'INSTALL_OK skills=%d source=%s destination=%s\n' "$installed" "$skill_source" "$skill_destination_root"
  bash "$repo_root/scripts/sync_project_memory_to_codex.sh"
fi
