#!/bin/sh
# managed by desloppify install-hooks
set -eu

SCOPE=${DESLOPPIFY_HOOK_SCOPE:-diff}

run_desloppify() {
  if [ -x "./node_modules/.bin/desloppify" ]; then
    ./node_modules/.bin/desloppify "$@"
    return
  fi

  if command -v bunx >/dev/null 2>&1 && bunx --bun desloppify "$@"; then
    return
  fi

  if command -v desloppify >/dev/null 2>&1; then
    desloppify "$@"
    return
  fi

  printf '%s\n' '[desloppify] could not find the desloppify CLI. Install it locally or make bunx available.' >&2
  exit 1
}

resolve_pack() {
  if [ -n "${DESLOPPIFY_PACK:-}" ]; then
    printf '%s' "$DESLOPPIFY_PACK"
    return
  fi

  run_desloppify suggest-pack . 2>/dev/null || printf '%s' 'js-ts'
}

PACK=$(resolve_pack)

if [ "$SCOPE" = "repo" ]; then
  printf '\n[desloppify] scanning whole repo with pack %s...\n' "$PACK"
  OUTPUT=$(run_desloppify scan . --json --pack "$PACK" || true)
else
  printf '\n[desloppify] scanning staged changes with pack %s...\n' "$PACK"
  OUTPUT=$(run_desloppify scan . --staged --json --pack "$PACK" || true)
fi

printf '%s\n' "$OUTPUT"
printf '%s' "$OUTPUT" | run_desloppify hook-gate commit
