#!/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
#     (CROSSED by Phase 1's tail/replay, which need the nats CLI, and again
#     by checks, which needs the cue CLI —
#     graduation is now owed; recording the decision node is part of taking it.);
#   - its behavior gets subtle enough to need real tests
#     (CROSSED by checks: glob matching is pinned by the policy-deriver
#     flake check, not by reading the code.);
#   - it needs nontrivial parsing or concurrency
#     (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
# The size tripwire (~300 lines) is crossed too. Which way to take the
# graduation is dcr-2aa1a12, still `proposed`.
# 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
  checks [<base> [<head>]]
                   print the check names the change between two commits owes
                   under the composed verification policy (dcr-f41f718), and
                   which class made each one required. It prints: no check is
                   run, nothing is gated, nothing is written.
                   base defaults to the merge base with main, head to HEAD.
                   the policy layers are not discovered — they are named:
                     --schema FILE    default schema/verification.cue
                     --instance DIR   default examples/policy/instance
                     --project DIR    default examples/policy/project
                   all three relative to the repository root.
  tail [subject]   watch bus events scroll by (default subject: valley.>);
                   the server comes from the nats CLI's own config
                   (NATS_URL or a nats context; default localhost)
  replay [dir]     publish one ref-updated event per current ref of the
                   repo at dir (default: .) — rebuilds the stream's
                   projection, e.g. after nats stream purge valley
  help             show this help

Runs from any checkout of the project; needs only git and coreutils,
except tail and replay, which also need the nats CLI (natscli), and
checks, which also needs the cue CLI.
No config, no state, no batch mode — the judgment stays with the human.
EOF
}

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

# Resolve the pager as git would for a diff: pager.diff first (per-command
# pager configs — e.g. home-manager's delta module — set pager.diff and leave
# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
# less). pager.<cmd> may legally be a boolean; treat true/false — and an
# empty or missing value — as unset and fall back. The value is
# shell-interpreted, hence sh -c; a non-tty just cats.
run_pager() {
  [ -t 1 ] || { cat; return; }
  local pager
  pager="$(git config --get pager.diff || true)"
  case "$pager" in ''|true|false) pager="$(git var GIT_PAGER)" ;; esac
  sh -c "$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
}

# tail and replay are thin wrappers over the nats CLI — anything they do,
# plain nats and git can do. They are the only verbs needing more than git
# and coreutils.
need_nats() {
  command -v nats >/dev/null 2>&1 \
    || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
}

cmd_tail() {
  [ $# -le 1 ] || die "usage: valley tail [subject]"
  need_nats
  exec nats sub "${1:-valley.>}"
}

# One ref-updated event per existing ref, from git for-each-ref alone. A
# ref's prior value is not derivable from the repository, so `old` is the
# all-zero id — the same payload a push creating the ref would produce.
# The payload construction mirrors the host module's publisher hook
# (nix/valley-host.nix); change one only with the other.
cmd_replay() {
  [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
  need_nats
  local dir="${1:-.}" repo sha ref event count=0
  git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
    || die "not a git repository: $dir"
  if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
    repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
  else
    repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
  fi
  while read -r sha ref; do
    # " is the only JSON-significant character a refname can contain (git
    # forbids \ and control characters); names and object ids are safe.
    event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
      "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
    nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
    count=$((count + 1))
  done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
  echo "replayed $count refs of $repo onto the bus"
}

# ----------------------------------------------------------------------
# checks — the verification-policy deriver (dcr-f41f718). It composes the
# instance layer with the project layer, matches every side of a diff
# against the composed classes, and prints the check names the change owes
# with the class or classes that made each one required. It reports: no
# check is run, nothing is gated, nothing is written.
#
# Composition is CUE's, never this script's. The whole of the mandatory-
# versus-overridable distinction is unification, so reimplementing it here
# would be reimplementing the decision. What this script does that CUE
# cannot is glob matching and reading a diff.

need_cue() {
  command -v cue >/dev/null 2>&1 \
    || die "this verb needs the cue CLI; nix run .#valley bundles it"
}

# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
# cross a `/`, and every ERE metacharacter is escaped.
segment_ere() {
  local seg="$1" out="" i c
  for ((i = 0; i < ${#seg}; i++)); do
    c="${seg:i:1}"
    case "$c" in
      '*') out+='[^/]*' ;;
      '?') out+='[^/]' ;;
      '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
      *) out+="$c" ;;
    esac
  done
  printf '%s' "$out"
}

# A path glob as an anchored ERE, segment by segment. A `**` segment matches
# any number of segments including none, so it swallows the separator that
# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
# matches exactly one.
glob_ere() {
  local ere='^' i last
  local -a segs=()
  IFS=/ read -r -a segs <<<"$1"
  last=$((${#segs[@]} - 1))
  for ((i = 0; i <= last; i++)); do
    if [ "${segs[i]}" = '**' ]; then
      if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
    else
      ere+="$(segment_ere "${segs[i]}")"
      [ "$i" -eq "$last" ] || ere+='/'
    fi
  done
  printf '%s$' "$ere"
}

# The composed policy as one tab-separated line per covered pattern and per
# required check, so the shell never parses CUE. The field is hidden because
# the schema's sentinel rejects unknown top-level fields, and `unclassified`
# is rendered as a class of that name — it is one more source a check can
# come from.
render_cue() {
  cat <<'EOF'
package verification

import (
	"list"
	"strings"
)

_render: strings.Join(list.Concat([[
	for cn, c in policy.classes
	for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
], [
	for cn, c in policy.classes
	for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
], [
	for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
]]), "\n")
EOF
}

# The composed layer, and a scratch directory for the documents this verb
# writes into the composition. Globals so the probe below can see them.
POLICY_LAYER=()
POLICY_TMP=""

# Is this check mandatory in this class, or a default the project left
# alone? The bit is the form of the composed value, so the test is CUE's
# own: a project supplying `false` either conflicts or unifies cleanly.
# Answering by unifying rather than by inspecting syntax means the script
# cannot disagree with `cue vet`.
check_is_mandatory() {
  local class="$1" check="$2" field
  if [ "$class" = unclassified ]; then
    field="policy: unclassified: \"$check\": false"
  else
    field="policy: classes: \"$class\": requires: \"$check\": false"
  fi
  printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue"
  ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
}

# Every side of the diff: an added, modified or deleted path, and both the
# old and the new path of a rename or copy. -z because a path may contain
# anything but NUL.
diff_paths() {
  local base="$1" head="$2" status path
  while IFS= read -r -d '' status; do
    IFS= read -r -d '' path || die "truncated diff output; nothing derived"
    printf '%s\n' "$path"
    case "$status" in
      R* | C*)
        IFS= read -r -d '' path || die "truncated diff output; nothing derived"
        printf '%s\n' "$path"
        ;;
    esac
  done < <(git diff --no-relative --name-status -M -z "$base" "$head")
}

# Lines in, one comma-separated line out.
join_lines() {
  local out="" line
  while IFS= read -r line; do out="${out:+$out, }$line"; done
  printf '%s' "$out"
}

# The ref a branch is derived against, preferring what origin last said.
main_ref() {
  git rev-parse --verify --quiet refs/remotes/origin/main > /dev/null \
    && { echo refs/remotes/origin/main; return; }
  git rev-parse --verify --quiet refs/heads/main > /dev/null \
    && { echo refs/heads/main; return; }
  return 1
}

cmd_checks() {
  local root schema instance project base head
  root="$(git rev-parse --show-toplevel 2> /dev/null)" \
    || die "not a git repository"
  schema="$root/schema/verification.cue"
  instance="$root/examples/policy/instance"
  project="$root/examples/policy/project"
  while [ $# -gt 0 ]; do
    case "$1" in
      --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
      --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
      --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
      --) shift; break ;;
      -*) die "unknown option: $1" ;;
      *) break ;;
    esac
  done
  [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"

  need_cue
  [ -f "$schema" ] || die "no policy schema at $schema"
  compgen -G "$instance/*.cue" > /dev/null \
    || die "no instance policy layer at $instance"
  compgen -G "$project/*.cue" > /dev/null \
    || die "no project policy layer at $project"

  head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
    || die "no such commit: ${2:-HEAD}"
  if [ $# -ge 1 ]; then
    base="$(git rev-parse --verify --quiet "$1^{commit}")" \
      || die "no such commit: $1"
  else
    local against
    against="$(main_ref)" || die "no main branch to derive a base from — name one"
    base="$(git merge-base "$against" "$head")" \
      || die "$head and ${against#refs/} do not share history — name a base"
  fi

  local -a paths=()
  mapfile -t paths < <(diff_paths "$base" "$head" | sort -u)

  POLICY_LAYER=("$schema" "$instance"/*.cue "$project"/*.cue)
  POLICY_TMP="$(mktemp -d)"
  # shellcheck disable=SC2064 # expand POLICY_TMP now, not at trap time
  trap "rm -rf '$POLICY_TMP'" EXIT
  render_cue > "$POLICY_TMP/render.cue"
  cue vet -c "${POLICY_LAYER[@]}" \
    || die "the policy layers do not compose; nothing derived"

  # Sorted once here, so every list below comes out in a stable order.
  local -a rendered=()
  mapfile -t rendered < <(cue eval --out text -e _render \
    "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" | sort)

  local -a pat_class=() pat_ere=() req_class=() req_check=()
  local line kind class value
  for line in "${rendered[@]}"; do
    kind="${line%%$'\t'*}"
    class="${line#*$'\t'}"
    value="${class#*$'\t'}"
    class="${class%%$'\t'*}"
    case "$kind" in
      path)
        pat_class+=("$class")
        pat_ere+=("$(glob_ere "$value")")
        ;;
      requires)
        req_class+=("$class")
        req_check+=("$value")
        ;;
    esac
  done

  local -A matched=()
  local -a uncovered=()
  local path i hit
  for path in "${paths[@]}"; do
    hit=0
    for ((i = 0; i < ${#pat_ere[@]}; i++)); do
      if [[ "$path" =~ ${pat_ere[i]} ]]; then
        matched["${pat_class[i]}"]=1
        hit=1
      fi
    done
    [ "$hit" -eq 1 ] || uncovered+=("$path")
  done
  # A path no class covers is answered by the policy's `unclassified` set,
  # which is why it is treated as one more matched class rather than as an
  # absence.
  [ "${#uncovered[@]}" -eq 0 ] || matched[unclassified]=1

  local -A owed=() pinned=()
  local check width=0 uncovered_owes=0
  for ((i = 0; i < ${#req_check[@]}; i++)); do
    class="${req_class[i]}"
    check="${req_check[i]}"
    [ -n "${matched[$class]:-}" ] || continue
    [ "$class" != unclassified ] || uncovered_owes=1
    owed["$check"]="${owed[$check]:+${owed[$check]}, }$class"
    if check_is_mandatory "$class" "$check"; then
      pinned["$check"]=mandatory
    else
      pinned["$check"]="${pinned[$check]:-default}"
    fi
    [ "${#check}" -le "$width" ] || width="${#check}"
  done

  printf '%s..%s: %d changed path(s)\n' \
    "$(git rev-parse --short "$base")" "$(git rev-parse --short "$head")" \
    "${#paths[@]}"
  printf 'policy: %s + %s\n' "${instance#"$root"/}" "${project#"$root"/}"
  if [ "${#matched[@]}" -eq 0 ]; then
    printf 'classes matched: none\n\n'
  else
    printf 'classes matched: %s\n\n' \
      "$(printf '%s\n' "${!matched[@]}" | sort | join_lines)"
  fi

  if [ "${#owed[@]}" -eq 0 ]; then
    echo "required checks: none"
  else
    echo "required checks:"
    while IFS= read -r check; do
      printf '  %-*s  %-9s  %s\n' \
        "$width" "$check" "${pinned[$check]}" "${owed[$check]}"
    done < <(printf '%s\n' "${!owed[@]}" | sort)
  fi

  if [ "${#uncovered[@]}" -gt 0 ]; then
    printf '\nunclassified: %d path(s) matched no class\n' "${#uncovered[@]}"
    printf '  %s\n' "${uncovered[@]}"
    # The failure the `unclassified` field exists to prevent: paths outside
    # every class that the policy then asks nothing of.
    [ "$uncovered_owes" -eq 1 ] \
      || echo "  the policy requires nothing of them — it is behind the tree"
  fi
}

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 "$@" ;;
    checks) cmd_checks "$@" ;;
    tail) cmd_tail "$@" ;;
    replay) cmd_replay "$@" ;;
    help | -h | --help) usage ;;
    *)
      printf 'valley: unknown verb: %s\n\n' "$verb" >&2
      usage >&2
      exit 1
      ;;
  esac
}

main "$@"
