#!/usr/bin/env bash
# Test double for the icloud-notes-sync CLI: canned answers, no Apple
# account, no network. The tests name it with ICLOUD_NOTES_SYNC_BIN,
# as the app finds the engine. Used by backend_test to exercise the exact
# argv/stdout/stderr/exit-code path the app uses in production.
#
# Output modes, as the real tool's (icloud_session::output): --quiet prints
# only the result's data on stdout; --json (or no flag: the stub's stdout
# is never a terminal) the envelope {"ok":true,"data","summary"}; --styled
# text. In --quiet/--json a failure is the contract error object
# {"ok":false,"error":{code,message,hint?}} on stdout, pretty-printed over
# several lines (here sometimes with its keys sorted: key order and layout
# are not part of the contract), and stderr carries no JSON; in --styled it
# is "error: ..." / "hint: ..." on stderr. Progress and notices go to
# stderr. status, push --dry-run and diff report their changes in the
# result and exit 0, a sign-in required exits 3, a usage error 2, offline 5
# (the codes every iCloud tool shares). vault-info is the real engine's
# ($ICLOUD_NOTES_SYNC_REAL, which bin/test builds): it reads the test's
# vault as the app would.
#
# ICLOUD_NOTES_SYNC_STUB_EXIT=N (with ICLOUD_NOTES_SYNC_STUB_ERROR=CODE,
# default "internal", and optionally ICLOUD_NOTES_SYNC_STUB_MESSAGE /
# ICLOUD_NOTES_SYNC_STUB_HINT): sync, pull, push, clone, diff, status and
# history fail at once with exit N and that error, giving no answer, as the
# engine does for a vault it cannot use (not_cloned_directory,
# account_mismatch, ...). The real `sync` gives no answer only when it never
# starts (vault_busy, vault_lock, usage): a vault it cannot use fails each
# half inside its answer, which is ICLOUD_NOTES_SYNC_STUB_PUSH_FAIL/PULL_FAIL
# here. pull, push and clone print progress lines first, as the real engine
# does in a machine mode. The success results are markers the tests look
# for ({"stub":"pull","ok":true}), not the engine's shapes: cli_test's last
# part runs the real engine on recorded answers for those.
# ICLOUD_NOTES_SYNC_STUB_PUSH_REFUSED=1: a push (alone, or as a sync's half)
# runs but has a change refused by iCloud: its result with the failed entry,
# exit 1, and in a sync the half's error `push_rejected` beside the result.
# ICLOUD_NOTES_SYNC_STUB_PUSH_SKIPPED=1: a push (alone, or as a sync's half)
# that left one change for the next push (outcome.skipped): it worked.
# ICLOUD_NOTES_SYNC_STUB_TOO_MANY=1: a push (alone, or as a sync's half)
# refuses to delete most of the vault (too_many_deletions, exit 2, with the
# engine's message and hint) unless it is run with --yes; a sync's pull runs
# all the same. --yes is taken by push and sync, and logged ("sync --yes").
# ICLOUD_NOTES_SYNC_STUB_GATE=FILE: a sync, pull or push waits while FILE
# exists, so a test decides when it ends (and changes the vault meanwhile).
orig=("$@")
gate() {
  [ -n "${ICLOUD_NOTES_SYNC_STUB_GATE:-}" ] || return 0
  while [ -e "$ICLOUD_NOTES_SYNC_STUB_GATE" ]; do sleep 0.02; done
}
quiet="" json="" styled="" ids="" count="" yes=""
args=()
while [ $# -gt 0 ]; do
  case "$1" in
    --yes) yes=1 ;;
    --quiet) quiet=1 ;;
    --json) json=1 ;;
    --styled) styled=1 ;;
    --ids-only) ids=1 ;;
    --count) count=1 ;;
    --wait) shift ;;
    *) args+=("$1") ;;
  esac
  shift
done
set -- "${args[@]}"
# Precedence ids-only > count > quiet > json > styled > (not a terminal:
# the envelope). --ids-only prints "stub-id", --count "1", whatever the
# command (the tests only check they are passed through).
if [ -n "$ids" ]; then mode=ids
elif [ -n "$count" ]; then mode=count
elif [ -n "$quiet" ]; then mode=quiet
elif [ -n "$json" ] || [ -z "$styled" ]; then mode=json
else mode=text
fi

# result JSON [TEXT] [META]: the result in the run's mode; META (a JSON
# object) is the envelope's meta, as the real tool's clone/pull/push
# ({"lines":[...]}) and diff ({"text":...}) carry their text report.
result() {
  case "$mode" in
    ids) echo stub-id ;;
    count) echo 1 ;;
    quiet) printf '%s\n' "$1" ;;
    json)
      if [ -n "${3:-}" ]; then printf '{"ok":true,"data":%s,"summary":"stub","meta":%s}\n' "$1" "$3"
      else printf '{"ok":true,"data":%s,"summary":"stub"}\n' "$1"
      fi ;;
    text) printf '%s\n' "${2:-stub}" ;;
  esac
}
# fail CODE MESSAGE HINT EXIT [sorted]: the failure in the run's mode, then exit.
fail() {
  if [ "$mode" = text ]; then
    echo "error: $2" >&2
    [ -n "$3" ] && echo "hint: $3" >&2
  elif [ -n "${5:-}" ]; then
    printf '{\n  "error": {\n    "code": "%s",\n' "$1"
    [ -n "$3" ] && printf '    "hint": "%s",\n' "$3"
    printf '    "message": "%s"\n  },\n  "ok": false\n}\n' "$2"
  else
    printf '{\n  "ok": false,\n  "error": {\n    "code": "%s",\n    "message": "%s"' "$1" "$2"
    [ -n "$3" ] && printf ',\n    "hint": "%s"' "$3"
    printf '\n  }\n}\n'
  fi
  exit "$4"
}
stub_fail() {
  [ -n "${ICLOUD_NOTES_SYNC_STUB_EXIT:-}" ] || return 0
  local code="${ICLOUD_NOTES_SYNC_STUB_ERROR:-internal}"
  local message="${ICLOUD_NOTES_SYNC_STUB_MESSAGE:-stub failure}"
  echo "stub: failing with $code" >&2
  fail "$code" "$message" "${ICLOUD_NOTES_SYNC_STUB_HINT:-}" "$ICLOUD_NOTES_SYNC_STUB_EXIT" sorted
}
# progress N: the engine's machine-mode progress on stderr (one line per
# fetched page and per processed note), which nobody's log should show.
progress() {
  [ "$mode" = text ] && return 0
  echo "icloud-notes:progress:fetch:$1" >&2
  echo "icloud-notes:progress:process-start:$1" >&2
  local i
  for i in $(seq 1 "$1"); do echo "icloud-notes:progress:process:$i/$1" >&2; done
}
# The shared wording (icloud_session::output).
sign_in_message='sign in to iCloud required'
sign_in_hint='run `icloud-session sign-in` (a person signs in in the window)'
rejected_message='Apple refused the iCloud session although icloud-sessiond still holds it (HTTP 401)'
refused_message='Notes/Big.md: server rejected the delete: BAD_REQUEST'
refused_result='{"dryRun":false,"pushed":0,"entries":[{"kind":"delete","file":"Notes/Big.md","resolution":"ready","outcome":{"succeeded":false,"message":"'"$refused_message"'"}}],"unchanged":1,"notices":[]}'
refused_lines='["'"$refused_message"'","Pushed 0 note(s)"]'
skipped_message='Notes/Alpha.md: changed here while it was being pushed - left for the next push'
skipped_result='{"dryRun":false,"pushed":0,"entries":[{"kind":"update","file":"Notes/Alpha.md","resolution":"ready","outcome":{"succeeded":true,"message":"'"$skipped_message"'","skipped":true}}],"unchanged":1,"notices":[]}'
skipped_lines='["'"$skipped_message"'","Pushed 0 note(s)"]'
too_many_message='5 of the 6 notes tracked here have no file any more (or an empty one). Pushing that would move them all to Recently Deleted, so nothing was pushed.'
too_many_hint='If the files went missing by accident (a folder moved, a disk not mounted, a sync tool'"'"'s mistake), put them back and sync again; \"icloud-notes push --dry-run\" lists what would be deleted. To delete them, run \"icloud-notes push --yes\".'

if [ "$1" = "vault-info" ]; then
  # ICLOUD_NOTES_SYNC_STUB_VAULT_INFO_LOG: a file each vault-info appends a line to.
  [ -n "${ICLOUD_NOTES_SYNC_STUB_VAULT_INFO_LOG:-}" ] && echo "vault-info" >> "$ICLOUD_NOTES_SYNC_STUB_VAULT_INFO_LOG"
  # ICLOUD_NOTES_SYNC_STUB_VAULT_INFO_FAIL: vault-info gives no answer (as a crash would).
  [ -n "${ICLOUD_NOTES_SYNC_STUB_VAULT_INFO_FAIL:-}" ] && exit 1
  exec "${ICLOUD_NOTES_SYNC_REAL:?bin/test names the real engine}" "${orig[@]}"
elif [ "$1" = "sync" ]; then
  # Push, then pull, in one run: {push, pull, vault_info}, each half
  # {ok, exit_code, result, lines} or {ok, exit_code, error}; a failed half
  # is reported there only. The pull is left out (null) after a refused
  # sign-in or an offline push, as the real tool does. The same switches as
  # pull/push below, plus ICLOUD_NOTES_SYNC_STUB_OFFLINE=1 (the push finds
  # no network) and ICLOUD_NOTES_SYNC_STUB_PULL_ADDS=FILE (the pull writes
  # that note and reports it, as a pull from iCloud would).
  # ICLOUD_NOTES_SYNC_STUB_PUSH_FAIL / ICLOUD_NOTES_SYNC_STUB_PULL_FAIL=CODE:EXIT
  # (sync only, before the other switches): that half fails with that code
  # and exit; the run exits by the engine's worse-half rule (3 if either
  # half exited 3, else the higher), and a push failing sign_in_required,
  # session_rejected, offline or network leaves the pull out.
  [ -n "${ICLOUD_NOTES_SYNC_STUB_LOG:-}" ] && echo "sync${yes:+ --yes}" >> "$ICLOUD_NOTES_SYNC_STUB_LOG"
  [ -n "${ICLOUD_NOTES_SYNC_STUB_SLEEP:-}" ] && sleep "$ICLOUD_NOTES_SYNC_STUB_SLEEP"
  gate
  stub_fail
  code=0
  half() { # half VERB: prints that half's JSON
    local forced
    [ "$1" = push ] && forced="${ICLOUD_NOTES_SYNC_STUB_PUSH_FAIL:-}" || forced="${ICLOUD_NOTES_SYNC_STUB_PULL_FAIL:-}"
    if [ -n "$forced" ]; then
      printf '{"ok":false,"exit_code":%s,"error":{"code":"%s","message":"stub %s failed with %s"}}' \
        "${forced#*:}" "${forced%%:*}" "$1" "${forced%%:*}"
      return
    fi
    if [ "$1" = push ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_OFFLINE:-}" ]; then
      printf '{"ok":false,"exit_code":5,"error":{"code":"offline","message":"offline: dns error: no network"}}'
      return
    fi
    if [ "$1" = push ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_PUSH_REFUSED:-}" ]; then
      printf '{"ok":false,"exit_code":1,"result":%s,"lines":%s,"error":{"code":"push_rejected","message":"%s"}}' \
        "$refused_result" "$refused_lines" "$refused_message"
      return
    fi
    if [ "$1" = push ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_TOO_MANY:-}" ] && [ -z "$yes" ]; then
      printf '{"ok":false,"exit_code":2,"error":{"code":"too_many_deletions","message":"%s","hint":"%s"}}' "$too_many_message" "$too_many_hint"
      return
    fi
    if [ "$1" = push ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_PUSH_SKIPPED:-}" ]; then
      printf '{"ok":true,"exit_code":0,"result":%s,"lines":%s}' "$skipped_result" "$skipped_lines"
      return
    fi
    if [ "${ICLOUD_NOTES_SYNC_STUB_EXPIRED:-}" = 1 ] || [ "${ICLOUD_NOTES_SYNC_STUB_EXPIRED:-}" = "$1" ]; then
      if [ "${ICLOUD_NOTES_SYNC_STUB_SIGNIN:-}" = rejected ]; then
        printf '{"ok":false,"exit_code":3,"error":{"code":"session_rejected","message":"%s","hint":"%s"}}' "$rejected_message" "$sign_in_hint"
      elif [ "${ICLOUD_NOTES_SYNC_STUB_SIGNIN:-}" = marker ]; then
        printf '{"ok":false,"exit_code":1,"error":{"code":"internal","message":"Run \\"icloud-md reauthenticate\\" to sign in interactively."}}'
      else
        printf '{"ok":false,"exit_code":3,"error":{"code":"sign_in_required","message":"%s","hint":"%s"}}' "$sign_in_message" "$sign_in_hint"
      fi
      return
    fi
    if [ "$1" = pull ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_PULL_ADDS:-}" ]; then
      mkdir -p "$(dirname "$ICLOUD_NOTES_SYNC_STUB_PULL_ADDS")"
      printf -- '# Added\nfrom iCloud\n' > "$ICLOUD_NOTES_SYNC_STUB_PULL_ADDS"
      printf '{"ok":true,"exit_code":0,"result":{"stub":"pull","ok":true,"added":1,"changes":[{"kind":"add","file":"%s"}]},"lines":["stub pull ok","added: %s"]}' \
        "$ICLOUD_NOTES_SYNC_STUB_PULL_ADDS" "$ICLOUD_NOTES_SYNC_STUB_PULL_ADDS"
      return
    fi
    [ "$1" = pull ] && echo "Fetching changes from iCloud..." >&2 && echo "icloud-notes:progress:fetch:3" >&2
    printf '{"ok":true,"exit_code":0,"result":{"stub":"%s","ok":true},"lines":["stub %s ok"]}' "$1" "$1"
  }
  push_json=$(half push)
  pull_json=null
  case "$push_json" in
    *'"code":"offline"'* | *'"code":"network"'* | *'"code":"sign_in_required"'* | *'"code":"session_rejected"'*) ;;
    *) pull_json=$(half pull) ;;
  esac
  # half_exit JSON: a half's exit_code (0 for none).
  half_exit() { local e; e=$(printf '%s' "$1" | sed -n 's/^{"ok":[a-z]*,"exit_code":\([0-9]*\).*/\1/p'); echo "${e:-0}"; }
  push_exit=$(half_exit "$push_json") pull_exit=$(half_exit "$pull_json")
  if [ "$push_exit" = 3 ] || [ "$pull_exit" = 3 ]; then code=3
  elif [ "$push_exit" -gt "$pull_exit" ]; then code=$push_exit
  else code=$pull_exit
  fi
  info=$("$ICLOUD_NOTES_SYNC_REAL" --quiet vault-info . 2>/dev/null) || info=null
  result "{\"push\":$push_json,\"pull\":$pull_json,\"vault_info\":${info:-null}}"
  exit "$code"
elif [ "$1" = "status" ]; then
  stub_fail
  echo "Fetching changes from iCloud..." >&2
  echo "icloud-notes:progress:fetch:12" >&2
  result '{"entries":[{"kind":"update","file":"A.md","resolution":"ready"},{"kind":"update","file":"B.md","resolution":"refused","reason":"B.md: has attachments"},{"kind":"createFolder","file":"New","resolution":"ready","folderTitle":"New"}],"unchanged":2,"notices":[{"level":"warn","message":"careful"}]}' \
    "Would update A.md"
  echo "Checked 5 notes." >&2
  exit 0
elif [ "$1" = "push" ] && [ "$2" = "--dry-run" ]; then
  # What icloud-notes push --dry-run passes through.
  result '{"entries":[{"kind":"update","file":"Notes/Alpha.md","resolution":"ready"}],"unchanged":1,"notices":[],"dryRun":true}' \
    "Would update Notes/Alpha.md"
  exit 0
elif [ "$1" = "history" ]; then
  stub_fail
  [ "$mode" != text ] && echo "Reading history..." >&2
  if [ "$3" = "--records" ]; then
    result '{"mode":"records","records":[{"id":"r1","timestamp":"2026-09-01T00:00:00Z","label":"note","recordChangeTag":"t"}]}' \
      "r1  2026-09-01T00:00:00Z  $2"
  else
    result '{"mode":"epochs","epochs":[{"id":"e9","timestamp":"2026-09-01T00:00:00Z","changed":["A"],"carriedOver":[]}]}' \
      "e9  2026-09-01T00:00:00Z  changed: $2"
  fi
elif [ "$1" = "restore" ]; then
  # Stands for "back to the last synced copy": the file gets a marker line.
  printf 'restored\n' >> "$2"
  result "{\"file\":\"$2\"}" "Restored $2 to match the last synced copy."
elif [ "$1" = "clone" ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_EXIT:-}" ]; then
  progress 2
  stub_fail
elif [ "$1" = "clone" ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_CLONE:-}" ]; then
  # A clone into the last argument: the state file and one note.
  # ICLOUD_NOTES_SYNC_STUB_CLONE=partial then fails (cloudkit_request_failed,
  # exit 1), as the real clone that fails part way does: what it wrote is
  # recorded, for a pull to finish.
  dir="${@: -1}"
  mkdir -p "$dir/.icloud-notes" "$dir/Notes"
  echo '{"layoutVersion":4,"titleMode":"in-body","folders":{"DefaultFolder-CloudKit":{"name":"Notes","dirName":"Notes"}},"notes":{"id-c":{"file":"Notes/Cloned.md","recordChangeTag":"t","modificationDate":0}}}' > "$dir/.icloud-notes/state.json"
  printf -- '---\napple-note-id: id-c\n---\n# Cloned\n' > "$dir/Notes/Cloned.md"
  progress 3
  [ "$ICLOUD_NOTES_SYNC_STUB_CLONE" = partial ] && fail cloudkit_request_failed "Attachment download failed: HTTP 410" "" 1
  result '{"written":1}' "Cloned 1 notes" '{"lines":["Cloned 1 notes"]}'
elif [ "$1" = "diff" ]; then
  # The diff's text is only in meta.text (the real engine's epoch diff,
  # an id starting with "e", has no data.text at all: its text is spread
  # over sections), so a reader of data.text shows nothing.
  stub_fail
  echo "Fetching the current remote copy..." >&2
  text=$'--- remote\n+++ local\n- old\n+ new'
  meta='{"text":"--- remote\n+++ local\n- old\n+ new"}'
  case "$3" in
    e*) result "{\"kind\":\"epoch\",\"epochId\":\"$3\",\"hasDifferences\":true,\"sections\":[{\"label\":\"A\",\"skipped\":false,\"hasDifferences\":true,\"text\":\"- old\"}]}" "$text" "$meta" ;;
    *) result "{\"kind\":\"snapshot\",\"from\":\"$3\",\"to\":\"remote\",\"hasDifferences\":true}" "$text" "$meta" ;;
  esac
  exit 0
elif [ "$1" = "pull" ] || [ "$1" = "push" ]; then
  # ICLOUD_NOTES_SYNC_STUB_LOG: a file each pull/push appends its verb to.
  [ -n "${ICLOUD_NOTES_SYNC_STUB_LOG:-}" ] && echo "$1${yes:+ --yes}" >> "$ICLOUD_NOTES_SYNC_STUB_LOG"
  # ICLOUD_NOTES_SYNC_STUB_SLEEP: seconds a run takes.
  # ICLOUD_NOTES_SYNC_STUB_EXPIRED: 1 refuses every run, or "pull"/"push"
  # only that one (a push with nothing to send never asks iCloud).
  # ICLOUD_NOTES_SYNC_STUB_SIGNIN: how a refusal is reported: "code" exit 3
  # with plain text and no error object, whatever the mode (so no code);
  # "marker" exit 1 with only icloud-md's text marker, which the app no
  # longer takes for a sign-in; "rejected" exit 3 and the code
  # session_rejected (Apple refused a session icloud-session still holds;
  # the sync skips its pull after it too); unset, exit 3 and the code
  # sign_in_required, as the real tool does.
  # ICLOUD_NOTES_SYNC_STUB_TAKE_LOCK: the real engine takes the vault's lock
  # here (restore of a note that isn't there, so nothing changes): through
  # the descriptor the app handed down it must get it, without it it must
  # find the vault busy (its error object is on stdout).
  if [ -n "${ICLOUD_NOTES_SYNC_STUB_TAKE_LOCK:-}" ]; then
    with=$("$ICLOUD_NOTES_SYNC_REAL" --quiet --wait 0 restore no-such-note.md . 2>/dev/null)
    without=$(env -u ICLOUD_NOTES_LOCK_FD "$ICLOUD_NOTES_SYNC_REAL" --quiet --wait 0 restore no-such-note.md . 2>/dev/null)
    case "$with" in *vault_busy*) echo "stub: the engine found the vault busy despite the lock handed down" >&2; exit 1 ;; esac
    case "$without" in *vault_busy*) ;; *) echo "stub: the engine got the vault without the lock: $without" >&2; exit 1 ;; esac
  fi
  [ -n "${ICLOUD_NOTES_SYNC_STUB_SLEEP:-}" ] && sleep "$ICLOUD_NOTES_SYNC_STUB_SLEEP"
  gate
  [ "$1" = pull ] && progress 3
  stub_fail
  # ICLOUD_NOTES_SYNC_STUB_OFFLINE: iCloud out of reach, exit 5; the error
  # object (sorted keys) is the only place the code is.
  if [ -n "${ICLOUD_NOTES_SYNC_STUB_OFFLINE:-}" ]; then
    fail offline "offline: dns error: no network" "check the network connection and try again" 5 sorted
  fi
  if [ "${ICLOUD_NOTES_SYNC_STUB_EXPIRED:-}" = 1 ] || [ "${ICLOUD_NOTES_SYNC_STUB_EXPIRED:-}" = "$1" ]; then
    case "${ICLOUD_NOTES_SYNC_STUB_SIGNIN:-}" in
      code)
        echo "$sign_in_message" >&2
        exit 3 ;;
      marker)
        echo 'Run "icloud-md reauthenticate" to sign in interactively.' >&2
        exit 1 ;;
      rejected)
        fail session_rejected "$rejected_message" "$sign_in_hint" 3 ;;
      *)
        fail sign_in_required "$sign_in_message" "$sign_in_hint" 3 ;;
    esac
  fi
  if [ "$1" = push ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_PUSH_REFUSED:-}" ]; then
    result "$refused_result" "$refused_message" "{\"lines\":$refused_lines}"
    exit 1
  fi
  if [ "$1" = push ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_TOO_MANY:-}" ] && [ -z "$yes" ]; then
    fail too_many_deletions "$too_many_message" "$too_many_hint" 2
  fi
  if [ "$1" = push ] && [ -n "${ICLOUD_NOTES_SYNC_STUB_PUSH_SKIPPED:-}" ]; then
    result "$skipped_result" "$skipped_message" "{\"lines\":$skipped_lines}"
    exit 0
  fi
  result "{\"stub\":\"$1\",\"ok\":true}" "stub $1 ok" "{\"lines\":[\"stub $1 ok\"]}"
else
  echo "stub: unknown args: ${orig[*]}" >&2
  exit 2
fi
