#!/usr/bin/env bash
# valley — the S1 integrator's verbs, as a plain shell script.
#
# EVICTION CLAUSE (owner-ratified; the decision node is
# .the-valley/decisions/dcr-74c3158-valley-cli-lifecycle.md).
# This tool is deliberately a shell script: it runs from any checkout with
# nothing but git and coreutils — no machinery, the portability stance of
# ida-b9f646c. It GRADUATES to its own repo and a real language the moment
# ANY tripwire is crossed:
#   - it grows past ~300 lines;
#   - it needs persistent state, config, or a daemon;
#   - it needs dependencies beyond git + coreutils
#     (Phase 1's `valley tail` will trip this);
#   - its behavior gets subtle enough to need real tests;
#   - it needs nontrivial parsing or concurrency.
# Graduation is a deliberate act, recorded as a decision node.
# Precedent: klaus — born in cosmo, graduated deliberately.

set -euo pipefail

die() {
  printf 'valley: %s\n' "$*" >&2
  exit 1
}

usage() {
  cat <<'EOF'
valley — S1 integrator verbs for a valley project (direct-push mode)

usage: valley <verb> [args]

  pending          list branches on origin not merged into origin/main
  review <branch>  page through the branch's log and diff vs origin/main,
                   then choose:
                     [i]ntegrate  ff-only merge onto main, push origin main,
                                  delete the merged branch from origin
                     [r]eject     delete the remote branch (confirmed first)
                     [s]kip       do nothing
                   a stale branch (won't fast-forward from main) is first
                   offered:
                     [b]ase       rebase it onto origin/main in a throwaway
                                  worktree, push --force-with-lease, then
                                  re-review the diff that would actually land
  help             show this help

Runs from any checkout of the project; needs only git and coreutils.
No config, no state, no batch mode — the judgment stays with the human.
EOF
}

fetch_origin() {
  git fetch --prune --quiet origin
}

# Resolve the pager exactly as git does — git var GIT_PAGER honors core.pager
# (so a configured delta renders these diffs too), then GIT_PAGER, then PAGER,
# then less. The value is shell-interpreted, hence sh -c; a non-tty just cats.
run_pager() {
  [ -t 1 ] || { cat; return; }
  sh -c "$(git var GIT_PAGER)"
}

pending_line() {
  local ref="$1" age author ahead stat
  age="$(git log -1 --format='%cr' "$ref")"
  author="$(git log -1 --format='%an' "$ref")"
  ahead="$(git rev-list --count "origin/main..$ref")"
  stat="$(git diff --shortstat "origin/main...$ref")"
  stat="${stat# }"
  printf '%s | %s | %s | ahead %s | %s\n' \
    "${ref#origin/}" "$age" "$author" "$ahead" "${stat:-no file changes}"
}

cmd_pending() {
  [ $# -eq 0 ] || die "pending takes no arguments"
  fetch_origin
  local ref found=0
  while IFS= read -r ref; do
    case "$ref" in
      origin/HEAD | origin/main) continue ;;
    esac
    found=1
    pending_line "$ref"
  done < <(git for-each-ref --format='%(refname:short)' \
    --no-merged=origin/main refs/remotes/origin)
  [ "$found" -eq 1 ] || echo "nothing pending"
}

integrate() {
  local branch="$1" local_main origin_main
  local_main="$(git rev-parse --verify --quiet refs/heads/main)" \
    || die "no local main branch to fast-forward — nothing merged"
  origin_main="$(git rev-parse refs/remotes/origin/main)"
  [ "$local_main" = "$origin_main" ] \
    || die "local main is not at origin/main — sync it first; nothing merged"
  git merge-base --is-ancestor refs/heads/main "refs/remotes/origin/$branch" \
    || die "$branch does not fast-forward from main — resolve by hand; nothing merged"
  git checkout --quiet main
  git merge --ff-only --quiet "refs/remotes/origin/$branch"
  git push --quiet origin main
  echo "integrated $branch: main is now $(git rev-parse --short main), pushed to origin"
  # The branch tip is now an ancestor of the main just pushed, so deleting it
  # loses nothing; without this every integration leaves a fully-merged ghost
  # ref that later reads as a confusing "empty" branch. Best-effort: a failed
  # delete must not report the integration as failed.
  if git push --quiet origin --delete "$branch"; then
    echo "deleted merged branch $branch from origin"
  else
    printf 'valley: warning: could not delete origin/%s — delete it by hand\n' \
      "$branch" >&2
  fi
}

reject() {
  local branch="$1" answer
  printf 'really delete origin/%s? [y/N] ' "$branch"
  read -r answer || answer=""
  case "$answer" in
    y | Y | yes)
      git push --quiet origin --delete "$branch"
      echo "rejected $branch: deleted from origin"
      ;;
    *) echo "kept $branch" ;;
  esac
}

show_review() {
  local branch="$1"
  {
    printf 'branch %s, log against origin/main:\n\n' "$branch"
    git --no-pager log --oneline "origin/main..origin/$branch"
    printf '\n'
    git --no-pager diff "origin/main...origin/$branch"
  } | run_pager || true # quitting the pager early is not an error
}

# Throwaway worktree for review's [b]ase choice; a global so the traps can
# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
REBASE_WT=""
cleanup_rebase_wt() {
  [ -n "$REBASE_WT" ] || return 0
  git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
  git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
  rm -rf "$REBASE_WT"
  REBASE_WT=""
}

# Rebase origin/<branch> onto origin/main in an isolated worktree — the
# user's checkout is never touched — and push with a lease so a concurrently
# updated branch is never clobbered. Mechanics only; the judgment on the
# rebased diff stays with the human, back at the review prompt.
rebase_onto_main() {
  local branch="$1"
  REBASE_WT="$(mktemp -d)"
  trap cleanup_rebase_wt EXIT
  trap 'exit 130' INT TERM
  git worktree add --quiet --detach "$REBASE_WT" "refs/remotes/origin/$branch"
  if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
    cleanup_rebase_wt
    die "$branch conflicts with main — resolve by hand; nothing changed"
  fi
  if ! git -C "$REBASE_WT" push --quiet --force-with-lease \
    origin "HEAD:refs/heads/$branch"; then
    cleanup_rebase_wt
    die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
  fi
  cleanup_rebase_wt
  trap - EXIT INT TERM
  echo "rebased $branch onto origin/main, pushed with --force-with-lease"
}

cmd_review() {
  [ $# -eq 1 ] || die "usage: valley review <branch>"
  local branch="${1#origin/}" choice
  fetch_origin
  git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
    || die "no such branch on origin: $branch"
  show_review "$branch"
  # A stale branch can't integrate, and its pre-rebase diff is not what would
  # land; offer to rebase it mechanically, then re-review what actually would.
  while ! git merge-base --is-ancestor refs/remotes/origin/main \
    "refs/remotes/origin/$branch"; do
    printf '%s does not fast-forward from main: [b]ase onto main, [r]eject, [s]kip? ' \
      "$branch"
    read -r choice || die "stdin closed before an answer; nothing done"
    case "$choice" in
      b)
        rebase_onto_main "$branch"
        fetch_origin
        show_review "$branch"
        ;;
      r) reject "$branch" && return ;;
      s)
        echo "skipped $branch; nothing done"
        return
        ;;
      *) echo "answer b, r, or s" ;;
    esac
  done
  while true; do
    printf '%s: [i]ntegrate, [r]eject, [s]kip? ' "$branch"
    read -r choice || die "stdin closed before an answer; nothing done"
    case "$choice" in
      i) integrate "$branch" && return ;;
      r) reject "$branch" && return ;;
      s)
        echo "skipped $branch; nothing done"
        return
        ;;
      *) echo "answer i, r, or s" ;;
    esac
  done
}

main() {
  local verb="${1:-help}"
  if [ $# -gt 0 ]; then shift; fi
  # The verb set is mirrored in completions/ (valley.bash, _valley) —
  # update both when it changes.
  case "$verb" in
    pending) cmd_pending "$@" ;;
    review) cmd_review "$@" ;;
    help | -h | --help) usage ;;
    *)
      printf 'valley: unknown verb: %s\n\n' "$verb" >&2
      usage >&2
      exit 1
      ;;
  esac
}

main "$@"
