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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ZHCT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
MANIFEST="${ZHCTPROJECT_REPO_MANIFEST:-$ZHCT_ROOT/zhctprompt/control/zhctproject-repositories.csv}"

if [[ ! -f "$MANIFEST" ]]; then
  echo "Manifest not found: $MANIFEST" >&2
  exit 1
fi

mkdir -p "$ZHCT_ROOT/zhctproject"

echo "ZHCT root: $ZHCT_ROOT"
echo "Manifest: $MANIFEST"
echo

failures=0

while IFS=, read -r name local_path remote_url default_action notes; do
  if [[ "$name" == "name" || -z "${name// }" ]]; then
    continue
  fi

  if [[ "$default_action" != "pull_or_clone" ]]; then
    echo "SKIP $name: unsupported action '$default_action'"
    continue
  fi

  target="$ZHCT_ROOT/$local_path"
  echo "==> $name"

  if [[ -d "$target/.git" ]]; then
    if [[ -n "$(git -C "$target" status --porcelain)" ]]; then
      echo "FAIL $name: local changes exist, skip pull: $target" >&2
      failures=$((failures + 1))
      echo
      continue
    fi

    git -C "$target" fetch --prune origin
    git -C "$target" pull --ff-only
  elif [[ -e "$target" ]]; then
    echo "FAIL $name: path exists but is not a Git repository: $target" >&2
    failures=$((failures + 1))
  else
    git clone "$remote_url" "$target"
  fi

  echo
done < "$MANIFEST"

if [[ "$failures" -gt 0 ]]; then
  echo "Completed with $failures failure(s)." >&2
  exit 1
fi

echo "All zhctproject repositories are present and up to date."
