#!/usr/bin/env bash
# bg: kleine BlueGit-CLI voor mensen en agents. Alleen bash, curl en jq.
#
#   BLUEGIT_URL    standaard https://git.timfalken.com
#   BLUEGIT_TOKEN  optioneel; nodig voor schrijven en voor privé projecten.
#                  Wordt nooit geprint.
#
# Zie docs/agents.md of `bg help`.
set -euo pipefail

BASE="${BLUEGIT_URL:-https://git.timfalken.com}"
BASE="${BASE%/}"
API="$BASE/api/v1"

die() { echo "bg: $*" >&2; exit 64; }
command -v curl >/dev/null || die "curl ontbreekt"
command -v jq >/dev/null || die "jq ontbreekt"

# req METHOD PATH [JSON] -> body op stdout; bij HTTP >= 400 de fout op stderr en exit 1.
req() {
  local method=$1 path=$2 data=${3:-} out code
  local args=(-sS -X "$method" -w '\n%{http_code}' -H "Accept: application/json")
  [[ -n "${BLUEGIT_TOKEN:-}" ]] && args+=(-H "Authorization: Bearer ${BLUEGIT_TOKEN}")
  [[ -n "$data" ]] && args+=(-H "Content-Type: application/json" --data-binary "$data")
  out=$(curl "${args[@]}" "$API$path") || { echo "bg: verbinding mislukt: $method $path" >&2; return 1; }
  code=${out##*$'\n'}
  out=${out%$'\n'*}
  if (( code >= 400 )); then
    local msg
    msg=$(printf '%s' "$out" | jq -r '.message // .error // empty' 2>/dev/null || true)
    echo "bg: HTTP $code bij $method $path${msg:+: $msg}" >&2
    [[ $code == 404 ]] && echo "bg: (bestaat niet, of je hebt geen toegang)" >&2
    return 1
  fi
  printf '%s' "$out"
}
get() { req GET "$1"; }
enc() { jq -rn --arg v "$1" '$v|@uri'; }
proj() { [[ "$1" == */* ]] || die "project moet owner/repo zijn: $1"; echo "/projects/$1"; }
issues() { echo "/repos/$1/issues"; }
json() { jq -cn "$@"; }

# ---------- pipelines ----------

# select_pipeline PROJECT ARGS... -> pipeline-JSON (of leeg als er nog geen is)
select_query() {
  local q=""
  while (($#)); do
    case $1 in
      --sha) q="sha=$2"; shift 2 ;;
      --mr) q="mr=$2"; shift 2 ;;
      --branch|--ref) q="ref=$(enc "$2")"; shift 2 ;;
      --id) q="id=$2"; shift 2 ;;
      --timeout|--interval) shift 2 ;;
      *) die "onbekende optie: $1" ;;
    esac
  done
  echo "$q"
}
find_pipeline() {
  local p=$1 q=$2
  if [[ $q == id=* ]]; then get "$(proj "$p")/pipelines/${q#id=}"; return; fi
  get "$(proj "$p")/pipelines?per_page=1${q:+&$q}" | jq -c '.[0] // empty'
}
show_pipeline() {
  local p=$1 pipe=$2
  jq -r '"pipeline #\(.id) \(.status)  \(.ref|sub("^refs/heads/";""))  \(.sha[0:8])  \(.web_url)"' <<<"$pipe"
  get "$(proj "$p")/pipelines/$(jq -r .id <<<"$pipe")/jobs" |
    jq -r '.[] | "  \(.id)\t\(.status)\t\(.stage)/\(.name)\(if .allow_failure then " (allow_failure)" else "" end)"'
}
failed_logs() {
  local p=$1 id=$2 jobs
  jobs=$(get "$(proj "$p")/pipelines/$id/jobs")
  jq -r '.[]|select(.status=="failed" and .allow_failure)|"bg: waarschuwing: \(.name) (#\(.id)) faalde (allow_failure)"' <<<"$jobs" >&2
  for j in $(jq -r '.[]|select(.status=="failed" and (.allow_failure|not))|.id' <<<"$jobs"); do
    echo "----- log job $j (laatste ${BG_LOG_LINES:-80} regels) -----" >&2
    get "$(proj "$p")/pipelines/$id/jobs/$j/log" | tail -n "${BG_LOG_LINES:-80}" >&2 || true
  done
}
cmd_pipeline() {
  local sub=${1:-}; shift || true
  case $sub in
    status)
      local p=${1:?project}; shift
      local q pipe; q=$(select_query "$@")
      pipe=$(find_pipeline "$p" "$q")
      [[ -n "$pipe" ]] || { echo "geen pipeline gevonden" >&2; exit 3; }
      show_pipeline "$p" "$pipe" ;;
    wait)
      local p=${1:?project}; shift
      local timeout=1800 interval=10 a=("$@")
      while (($#)); do case $1 in --timeout) timeout=$2; shift 2 ;; --interval) interval=$2; shift 2 ;; *) shift ;; esac; done
      local q pipe status start=$SECONDS last=""
      q=$(select_query "${a[@]}")
      while :; do
        pipe=$(find_pipeline "$p" "$q" || true)
        status=$(jq -r '.status // empty' <<<"${pipe:-{\}}")
        if [[ -n "$status" && "$status" != "$last" ]]; then
          echo "pipeline #$(jq -r .id <<<"$pipe"): $status" >&2; last=$status
        fi
        case $status in
          success) show_pipeline "$p" "$pipe"; failed_logs "$p" "$(jq -r .id <<<"$pipe")" 2>&1 | grep '^bg: waarschuwing' >&2 || true; exit 0 ;;
          failed|canceled) show_pipeline "$p" "$pipe"; failed_logs "$p" "$(jq -r .id <<<"$pipe")"; exit 1 ;;
        esac
        (( SECONDS - start >= timeout )) && { echo "bg: timeout na ${timeout}s (status ${status:-geen pipeline})" >&2; exit 2; }
        sleep "$interval"
      done ;;
    logs) get "$(proj "${1:?project}")/pipelines/${2:?pipeline-id}/jobs/${3:?job-id}/log" ;;
    retry)
      local mode=failed
      [[ ${3:-} == --all ]] && mode=all
      req POST "$(proj "${1:?project}")/pipelines/${2:?pipeline-id}/retry" "$(json --arg m "$mode" '{mode:$m}')" | jq -r '"pipeline #\(.id) \(.status) \(.web_url)"' ;;
    list) get "$(proj "${1:?project}")/pipelines?per_page=${2:-10}" | jq -r '.[]|"\(.id)\t\(.status)\t\(.ref|sub("^refs/heads/";""))\t\(.sha[0:8])"' ;;
    *) die "pipeline status|wait|logs|retry|list" ;;
  esac
}

# ---------- merge requests ----------
cmd_mr() {
  local sub=${1:-}; shift || true
  case $sub in
    list)
      local p=${1:?project}; shift; local q="state=open"
      while (($#)); do case $1 in --state) q="state=$2"; shift 2 ;; --source) q+="&source_branch=$(enc "$2")"; shift 2 ;; --target) q+="&target_branch=$(enc "$2")"; shift 2 ;; *) die "onbekende optie $1" ;; esac; done
      get "$(proj "$p")/merge_requests?per_page=100&$q" | jq -r '.[]|"!\(.iid)\t\(.state)\t\(.source_branch) -> \(.target_branch)\t\(.title)"' ;;
    show) get "$(proj "${1:?project}")/merge_requests/${2:?nummer}" | jq . ;;
    create)
      local p=${1:?project}; shift; local src="" tgt="" title="" desc="" remove=true
      while (($#)); do case $1 in --source) src=$2; shift 2 ;; --target) tgt=$2; shift 2 ;; --title) title=$2; shift 2 ;; --description) desc=$2; shift 2 ;; --keep-source) remove=false; shift ;; *) die "onbekende optie $1" ;; esac; done
      [[ -n $src && -n $tgt && -n $title ]] || die "mr create PROJECT --source B --target B --title T [--description D] [--keep-source]"
      req POST "$(proj "$p")/merge_requests" "$(json --arg s "$src" --arg t "$tgt" --arg ti "$title" --arg d "$desc" --argjson r "$remove" '{source_branch:$s,target_branch:$t,title:$ti,description:$d,remove_source_branch:$r}')" | jq -r '"!\(.iid) \(.web_url)"' ;;
    merge)
      local remove=true; [[ ${3:-} == --keep-source ]] && remove=false
      req POST "$(proj "${1:?project}")/merge_requests/${2:?nummer}/merge" "$(json --argjson r "$remove" '{remove_source_branch:$r}')" | jq -r '"\(.state) \(.web_url)"' ;;
    comment) req POST "$(proj "${1:?project}")/merge_requests/${2:?nummer}/notes" "$(json --arg b "${3:?tekst}" '{body:$b}')" | jq -r '"notitie \(.id)"' ;;
    *) die "mr list|show|create|merge|comment" ;;
  esac
}

# ---------- issues ----------
cmd_issue() {
  local sub=${1:-}; shift || true
  case $sub in
    list) get "$(issues "${1:?project}")?state=${2:-open}" | jq -r '.issues[]|"#\(.id)\t\(.status)\t\(.title)"' ;;
    show) get "$(issues "${1:?project}")/${2:?nummer}" | jq . ;;
    create) req POST "$(issues "${1:?project}")" "$(json --arg t "${2:?titel}" --arg d "${3:-}" '{title:$t,description:$d}')" | jq -r '"#\(.id) \(.web_url)"' ;;
    comment) req POST "$(issues "${1:?project}")/${2:?nummer}/notes" "$(json --arg b "${3:?tekst}" '{body:$b}')" >/dev/null && echo "ok" ;;
    close|reopen)
      local st=closed; [[ $sub == reopen ]] && st=open
      req PUT "$(issues "${1:?project}")/${2:?nummer}" "$(json --arg s "$st" '{state:$s}')" | jq -r '"#\(.id) \(.status)"' ;;
    *) die "issue list|show|create|comment|close|reopen" ;;
  esac
}

# ---------- overig ----------
cmd_branch() {
  [[ ${1:-} == create ]] || die "branch create PROJECT NAAM [--from REF]"
  local p=${2:?project} name=${3:?naam} from=""
  [[ ${4:-} == --from ]] && from=${5:?ref}
  req POST "$(proj "$p")/repository/branches" "$(json --arg n "$name" --arg f "$from" '{name:$n} + (if $f=="" then {} else {from:$f} end)')" | jq -r '.name // .'
}
cmd_release() {
  [[ ${1:-} == create ]] || die "release create PROJECT TAG [--commit SHA] [--name N] [--body B] [--asset JOB:PAD[:NAAM]]..."
  local p=${2:?project} tag=${3:?tag}; shift 3
  local commit="" name="" body="" assets="[]"
  while (($#)); do case $1 in
    --commit) commit=$2; shift 2 ;; --name) name=$2; shift 2 ;; --body) body=$2; shift 2 ;;
    --asset) IFS=: read -r j pth nm <<<"$2"; assets=$(jq -c --arg j "$j" --arg p "$pth" --arg n "${nm:-}" '. + [{job:$j,path:$p} + (if $n=="" then {} else {name:$n} end)]' <<<"$assets"); shift 2 ;;
    *) die "onbekende optie $1" ;; esac; done
  req POST "$(proj "$p")/releases" "$(json --arg t "$tag" --arg c "$commit" --arg n "$name" --arg b "$body" --argjson a "$assets" '{tag:$t,commit:$c,name:$n,body:$b,assets:$a}')" | jq -c .
}
cmd_file() {
  [[ ${1:-} == get ]] || die "file get PROJECT PAD [--ref REF]"
  local p=${2:?project} path=${3:?pad} ref=""
  [[ ${4:-} == --ref ]] && ref="?ref=$(enc "${5:?ref}")"
  local body; body=$(get "$(proj "$p")/repository/files/$(enc "$path")$ref")
  if jq -e '.content and .encoding=="base64"' <<<"$body" >/dev/null 2>&1; then jq -r .content <<<"$body" | base64 -d
  elif jq -e '.content' <<<"$body" >/dev/null 2>&1; then jq -r .content <<<"$body"
  else printf '%s' "$body"; fi
}

usage() {
  sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'
  cat <<'U'

  bg pipeline status PROJECT [--sha X | --mr N | --branch B | --id P]
  bg pipeline wait   PROJECT [selectie] [--timeout 1800] [--interval 10]   exit 0 ok, 1 mislukt, 2 timeout
  bg pipeline logs   PROJECT PIPELINE JOB
  bg pipeline retry  PROJECT PIPELINE [--all]
  bg pipeline list   PROJECT [N]
  bg mr list|show|create|merge|comment ...
  bg issue list|show|create|comment|close|reopen ...
  bg branch create PROJECT NAAM [--from REF]
  bg release create PROJECT TAG [--commit SHA] [--asset JOB:PAD[:NAAM]]
  bg file get PROJECT PAD [--ref REF]
U
}

case ${1:-help} in
  pipeline|pl) shift; cmd_pipeline "$@" ;;
  mr) shift; cmd_mr "$@" ;;
  issue) shift; cmd_issue "$@" ;;
  branch) shift; cmd_branch "$@" ;;
  release) shift; cmd_release "$@" ;;
  file) shift; cmd_file "$@" ;;
  help|-h|--help) usage ;;
  *) usage >&2; exit 64 ;;
esac
