#!/usr/bin/env bash
#
# jira-family-write.sh  -  fetch the issue family of a Jira-started run, and
# apply the writes scripts/jira-family.mjs planned for it.
#
# The planning half is offline and testable; this half is the one that talks
# to Jira, so it stays small. Every write goes through jira-publish.sh, which
# escapes the body, runs the outbound gate and backs a description up before it
# replaces one. A write the plan marks `raw` (the story reformat: the author's
# lines plus escaped macros) is sent with --raw, so the author's lines reach
# Jira unchanged. Reads go through jira_api in _jira-auth.sh.
#
# A write is checked against the site right before it is sent:
#   comment      skipped when a comment by the authenticated user on the issue
#                already carries its marker
#   description  skipped when the story already conforms, or when it changed
#                since the plan read it (jira-publish.sh --expect-file)
# so running the same plan twice writes nothing the second time.
#
# Usage, from a run (the state file is agent-state.json; the family's files go
# to jira-family/ beside it):
#   jira-family-write.sh resolve --state FILE
#       fetch and resolve the family, record state.jiraFamily; no Jira write
#   jira-family-write.sh plan --state FILE --dev-body FILE [--skip id,id]
#                             [--dev-task KEY] [--test-task KEY] [--build TEXT]
#       re-resolve and plan; run id, PR URL and mode come from the state
#   jira-family-write.sh apply --state FILE [--dry-run]
#       apply jira-family/plan.json, write jira-family/writes.json, merge it
#       into state.jiraFamily.writes by write id
#
# Lower level:
#   jira-family-write.sh fetch --issue KEY --out DIR
#       DIR/input.json, DIR/story.json (the parent when KEY is a sub-task, else
#       the same issue), DIR/site-types.txt (empty when unreadable)
#   jira-family-write.sh apply --plan FILE [--state FILE] [--result FILE] [--dry-run]
#       --state   the plan's autopilot decisions are recorded there
#                 (decisions-log.mjs) once their write has gone out
#       --result  the per-write outcome as JSON, written on every exit
#
# Exit: 0 done, 3 the input does not parse or the plan still has questions,
#       4 auth (also when a write failed on auth), 5 a write failed (the others
#       went out; --result lists which, and a re-run sends only what is missing),
#       6 unattended (nothing read or written; the runner owns Jira),
#       64 usage or a malformed issue key.

set -uo pipefail

SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
. "$SELF_DIR/_jira-auth.sh"
# shellcheck source=/dev/null
. "$SELF_DIR/unattended.sh"

USAGE="usage:
  jira-family-write.sh resolve --state FILE
  jira-family-write.sh plan --state FILE --dev-body FILE [--skip id,id] [--dev-task KEY] [--test-task KEY] [--build TEXT]
  jira-family-write.sh apply --state FILE [--plan FILE] [--result FILE] [--dry-run]
  jira-family-write.sh fetch --issue KEY --out DIR
  jira-family-write.sh apply --plan FILE [--state FILE] [--result FILE] [--dry-run]"
usage() { echo "$USAGE" >&2; exit 64; }

CMD="${1:-}"; [ -n "$CMD" ] || usage; shift
case "$CMD" in -h|--help) awk 'NR==1{next} !/^#/{exit} {print}' "$0"; exit 0 ;; esac
ISSUE=""; OUT=""; PLAN=""; STATE=""; RESULT=""; DRY=0
DEV_BODY=""; SKIP=""; DEV_TASK=""; TEST_TASK=""; BUILD=""
while [ $# -gt 0 ]; do
  case "$1" in
    -h|--help) awk 'NR==1{next} !/^#/{exit} {print}' "$0"; exit 0 ;;
    --dev-body) DEV_BODY="${2:-}"; shift 2 ;;
    --skip) SKIP="${2:-}"; shift 2 ;;
    --dev-task) DEV_TASK="${2:-}"; shift 2 ;;
    --test-task) TEST_TASK="${2:-}"; shift 2 ;;
    --build) BUILD="${2:-}"; shift 2 ;;
    --issue) ISSUE="${2:-}"; shift 2 ;;
    --out) OUT="${2:-}"; shift 2 ;;
    --plan) PLAN="${2:-}"; shift 2 ;;
    --state) STATE="${2:-}"; shift 2 ;;
    --result) RESULT="${2:-}"; shift 2 ;;
    --dry-run) DRY=1; shift ;;
    *) usage ;;
  esac
done

command -v jq >/dev/null 2>&1 || { echo "ERR: jq is required" >&2; exit 3; }

FAMILY_MJS="$SELF_DIR/../scripts/jira-family.mjs"
DECISIONS_MJS="$SELF_DIR/../scripts/decisions-log.mjs"
PUBLISH="$SELF_DIR/jira-publish.sh"
FIELDS="summary,issuetype,parent,subtasks,description,project,status"

# A key goes into a REST path, so anything but a key is refused before use.
valid_key() { grep -Eq '^[A-Z][A-Z0-9_]+-[0-9]+$' <<<"$1"; }

# What a jira-publish.sh exit code means, for the result line.
publish_reason() {
  case "$1" in
    4) echo "Jira host or token could not be resolved (exit 4)" ;;
    5) echo "the Jira call failed (exit 5)" ;;
    64) echo "refused before sending, e.g. by the outbound gate (exit 64): $2" ;;
    *) echo "jira-publish.sh exit $1: $2" ;;
  esac
}

fetch_issue() {  # fetch_issue <key> <file>
  jira_api GET "/rest/api/2/issue/$1?fields=$FIELDS" > "$2" 2>/dev/null || return 5
  jq -e '.key' "$2" >/dev/null 2>&1 || return 5
}

do_fetch() {  # do_fetch <key> <dir>
  local issue="$1" out="$2" parent project
  valid_key "$issue" || { echo "ERR: not an issue key: $issue" >&2; return 64; }
  if ma_unattended; then
    echo "unattended run: the family is not read here; the runner owns Jira" >&2
    return 6
  fi
  jira_auth_resolve || return 4
  mkdir -p "$out"
  fetch_issue "$issue" "$out/input.json" || { echo "ERR: could not read $issue" >&2; return 5; }
  parent="$(jq -r 'if .fields.issuetype.subtask == true then .fields.parent.key // empty else empty end' "$out/input.json")"
  if [ -n "$parent" ] && ! valid_key "$parent"; then
    echo "WARN: the parent key does not look like a key: $parent" >&2; parent=""
  fi
  if [ -n "$parent" ]; then
    fetch_issue "$parent" "$out/story.json" || { echo "WARN: could not read the parent $parent" >&2; rm -f "$out/story.json"; }
  else
    cp "$out/input.json" "$out/story.json"
  fi
  project="$(jq -r '.fields.project.key // empty' "$out/input.json")"
  [ -n "$project" ] || project="${issue%%-*}"
  bash "$SELF_DIR/analysis-jira-write.sh" --subtask-types --project "$project" \
    > "$out/site-types.txt" 2>/dev/null || : > "$out/site-types.txt"
  echo "fetched $issue${parent:+ (story $parent)} into $out"
}

# The run's own files: the issue key and the family directory beside agent-state.json.
state_key() { jq -r '.jiraId // .taskId // empty' "$STATE"; }
family_dir() { printf '%s/jira-family' "$(cd "$(dirname "$STATE")" && pwd)"; }

do_resolve() {  # fetch, resolve, and record state.jiraFamily; asks and writes nothing in Jira
  local key dir story=""
  key="$(state_key)"; dir="$(family_dir)"
  do_fetch "$key" "$dir" >/dev/null || return $?
  [ -f "$dir/story.json" ] && story="--story $dir/story.json"
  # shellcheck disable=SC2086
  node "$FAMILY_MJS" resolve --input "$dir/input.json" $story \
    --site-types "$dir/site-types.txt" > "$dir/family.json" || return 3
}

if [ "$CMD" = "fetch" ]; then
  [ -n "$ISSUE" ] && [ -n "$OUT" ] || usage
  do_fetch "$ISSUE" "$OUT"
  exit $?
fi

WRITE_STATE="$SELF_DIR/../scripts/write-state.mjs"

if [ "$CMD" = "resolve" ]; then
  [ -n "$STATE" ] && [ -f "$STATE" ] || usage
  do_resolve || exit $?
  DIR="$(family_dir)"
  jq -n --slurpfile f "$DIR/family.json" --slurpfile s "$STATE" \
    '{jiraFamily: ($f[0].stateEntry + {writes: ($s[0].jiraFamily.writes // [])})}' \
    | node "$WRITE_STATE" "$STATE" || exit 3
  jq -r '"family: story \(.stateEntry.storyKey), dev \(.stateEntry.devTaskKey // "-"), test \(.stateEntry.testTaskKey // "-"), story format \(.stateEntry.storyFormat.status)"' "$DIR/family.json"
  exit 0
fi

if [ "$CMD" = "plan" ]; then
  [ -n "$STATE" ] && [ -f "$STATE" ] && [ -n "$DEV_BODY" ] && [ -f "$DEV_BODY" ] || usage
  do_resolve || exit $?
  DIR="$(family_dir)"
  RUN_ID="$(jq -r '"\(.taskId)-\(.shortId // 0)"' "$STATE")"
  PR_URL="$(jq -r '.pr.url // .projects[0].pr.url // empty' "$STATE")"
  MODE="$(jq -r 'if .autopilot == true then "autopilot" else "interactive" end' "$STATE")"
  set -- --family "$DIR/family.json" --dev-body "$DEV_BODY" --run-id "$RUN_ID" --mode "$MODE"
  [ -z "$PR_URL" ] || set -- "$@" --pr-url "$PR_URL"
  [ -z "$BUILD" ] || set -- "$@" --build "$BUILD"
  [ -z "$SKIP" ] || set -- "$@" --skip "$SKIP"
  [ -z "$DEV_TASK" ] || set -- "$@" --dev-task "$DEV_TASK"
  [ -z "$TEST_TASK" ] || set -- "$@" --test-task "$TEST_TASK"
  node "$FAMILY_MJS" plan "$@" > "$DIR/plan.json" || exit 3
  jq -r '.confirm, (.skipped[] | "  not written: \(.id) (\(.reason))"), (.questions[] | "  question \(.id): \(.question) [\(.options | join(", "))]")' "$DIR/plan.json"
  echo "plan: $DIR/plan.json"
  exit 0
fi

[ "$CMD" = "apply" ] || usage
MERGE=0
if [ -z "$PLAN" ] && [ -n "$STATE" ] && [ -f "$STATE" ]; then
  PLAN="$(family_dir)/plan.json"
  [ -n "$RESULT" ] || RESULT="$(family_dir)/writes.json"
  MERGE=1
fi
[ -n "$PLAN" ] && [ -f "$PLAN" ] || usage

# Every exit leaves a result file, so the caller's follow-up never reads nothing.
early_exit() {  # early_exit <code> <status> <reason>
  if [ -n "$RESULT" ]; then
    jq -c --arg s "$2" --arg r "$3" '[.writes[]? | {id, issue, status: $s, reason: $r}]' "$PLAN" \
      > "$RESULT" 2>/dev/null || echo '[]' > "$RESULT"
  fi
  exit "$1"
}
if ma_unattended; then
  echo "unattended run: the family writes are left to the runner" >&2
  early_exit 6 skipped "unattended run: left to the runner"
fi
jq -e . "$PLAN" >/dev/null 2>&1 || { echo "ERR: the plan does not parse: $PLAN" >&2; early_exit 3 failed "the plan does not parse"; }
if [ "$(jq -r '.ready' "$PLAN")" != "true" ]; then
  echo "ERR: the plan still has open questions ($(jq -r '[.questions[].id] | join(", ")' "$PLAN")); answer them and re-plan" >&2
  early_exit 3 skipped "the plan still has open questions"
fi
[ "$DRY" -eq 1 ] || jira_auth_resolve || exit 4

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
RESULTS="$WORK/results.jsonl"; : > "$RESULTS"
ME=""
RC=0

record() {  # record <id> <issue> <status> <reason>
  jq -cn --arg i "$1" --arg k "$2" --arg s "$3" --arg r "$4" \
    '{id: $i, issue: $k, status: $s, reason: $r}' >> "$RESULTS"
  printf '  %-8s %-12s %s%s\n' "$3" "$1" "$2" "${4:+  ($4)}"
}

fail_rc() {  # an auth failure (4) outranks any other failure (5) in the exit code
  if [ "$1" -eq 4 ]; then RC=4; elif [ "$RC" -ne 4 ]; then RC=5; fi
}

record_decisions() {  # record_decisions <writeId>, or "" for the decisions that made no write
  [ -n "$STATE" ] || return 0
  jq -c --arg w "$1" '.decisions[]? | select(if $w == "" then .writeId == null else .writeId == $w end)' "$PLAN" | while IFS= read -r d; do
    node "$DECISIONS_MJS" add --state "$STATE" \
      --what "$(printf '%s' "$d" | jq -r .what)" \
      --why "$(printf '%s' "$d" | jq -r .why)" \
      --cost-if-wrong "$(printf '%s' "$d" | jq -r .costIfWrong)" \
      --phase "$(printf '%s' "$d" | jq -r .phase)" >/dev/null 2>&1 \
      || echo "  WARN: could not record the decision for $1" >&2
  done
}

echo "jira-family: $(jq -r '.confirm' "$PLAN")$([ "$DRY" -eq 1 ] && echo "  (dry run)")"
N="$(jq '.writes | length' "$PLAN")"
i=0
while [ "$i" -lt "$N" ]; do
  W="$(jq -c ".writes[$i]" "$PLAN")"
  i=$((i + 1))
  id="$(printf '%s' "$W" | jq -r .id)"
  kind="$(printf '%s' "$W" | jq -r .kind)"
  issue="$(printf '%s' "$W" | jq -r .issue)"
  printf '%s' "$W" | jq -j .body > "$WORK/body.txt"
  if ! valid_key "$issue"; then
    record "$id" "$issue" "failed" "not an issue key"; RC=5; continue
  fi
  if [ "$DRY" -eq 1 ]; then
    record "$id" "$issue" "dry-run" "$kind"
    continue
  fi
  if [ "$kind" = "comment" ]; then
    mark="$(printf '%s' "$W" | jq -r .marker)"
    if ! jira_api GET "/rest/api/2/issue/$issue/comment?maxResults=1000" > "$WORK/comments.json" 2>/dev/null \
        || ! jq -e '.comments' "$WORK/comments.json" >/dev/null 2>&1; then
      record "$id" "$issue" "failed" "could not read the comments"; RC=5; continue
    fi
    if [ -z "$ME" ]; then
      jira_api GET "/rest/api/2/myself" > "$WORK/me.json" 2>/dev/null || :
      ME="$(jq -c '{name, key, accountId} | with_entries(select(.value != null))' "$WORK/me.json" 2>/dev/null || echo "")"
    fi
    if [ -z "$ME" ] || [ "$ME" = "{}" ]; then
      ME=""; record "$id" "$issue" "failed" "could not read the authenticated user"; RC=5; continue
    fi
    # Only our own comments count: another user can paste a marker, and it
    # must not be able to stop this one from being posted.
    seen="$(jq --arg m "$mark" --argjson me "$ME" '[.comments[]?
      | select((.author // {}) as $a | any($me | to_entries[]; $a[.key] == .value))
      | .body // "" | select(contains($m))] | length' "$WORK/comments.json")"
    if [ "${seen:-0}" -gt 0 ]; then
      record "$id" "$issue" "exists" "already posted by this run"; continue
    fi
    bash "$PUBLISH" --issue "$issue" --body-file "$WORK/body.txt" --target comment >/dev/null 2>"$WORK/err.txt"
    prc=$?
    if [ "$prc" -eq 0 ]; then
      record "$id" "$issue" "written" ""
      record_decisions "$id"
    else
      record "$id" "$issue" "failed" "$(publish_reason "$prc" "$(head -1 "$WORK/err.txt")")"
      fail_rc "$prc"
    fi
    continue
  fi
  # description
  if ! jira_api GET "/rest/api/2/issue/$issue?fields=description" > "$WORK/current.json" 2>/dev/null \
      || ! jq -e '.fields' "$WORK/current.json" >/dev/null 2>&1; then
    record "$id" "$issue" "failed" "could not read the description"; RC=5; continue
  fi
  jq -j '.fields.description // ""' "$WORK/current.json" > "$WORK/current.txt"
  printf '%s' "$W" | jq -j '.original // ""' > "$WORK/original.txt"
  jq '{global: {issueTree: (if .storyPanels == null then {} else {storyPanels: .storyPanels} end)}}' \
    "$PLAN" > "$WORK/plan-prefs.json"
  if node "$FAMILY_MJS" check --description "$WORK/current.txt" --prefs "$WORK/plan-prefs.json" >/dev/null 2>&1; then
    record "$id" "$issue" "exists" "already in the story format"; continue
  fi
  if ! cmp -s "$WORK/current.txt" "$WORK/original.txt"; then
    record "$id" "$issue" "skipped" "the description changed since the preview"; continue
  fi
  raw=""
  [ "$(printf '%s' "$W" | jq -r '.raw == true')" = "true" ] && raw="--raw"
  bash "$PUBLISH" --issue "$issue" --body-file "$WORK/body.txt" --target description \
    --mode replace --confirm-overwrite --expect-file "$WORK/original.txt" $raw >/dev/null 2>"$WORK/err.txt"
  prc=$?
  if [ "$prc" -eq 0 ]; then
    record "$id" "$issue" "written" "previous text backed up"
    record_decisions "$id"
  elif [ "$prc" -eq 6 ]; then
    record "$id" "$issue" "skipped" "the description changed since the preview"
  else
    record "$id" "$issue" "failed" "$(publish_reason "$prc" "$(head -1 "$WORK/err.txt")")"
    fail_rc "$prc"
  fi
done

[ "$DRY" -eq 1 ] || record_decisions ""
[ -z "$RESULT" ] || jq -s '.' "$RESULTS" > "$RESULT"
# Merged by write id: a re-run that finds a comment already there ("exists")
# keeps the earlier "written" record instead of replacing it.
if [ "$MERGE" -eq 1 ] && [ "$DRY" -eq 0 ]; then
  jq -n --slurpfile s "$STATE" --slurpfile n "$RESULT" '
    ($s[0].jiraFamily // {}) as $f
    | ($f.writes // []) as $old
    | ($n[0] | map({(.id): .}) | add // {}) as $new
    | ($old | map(.id)) as $oldIds
    | {jiraFamily: ($f + {writes: (
        [$old[] | . as $o | ($new[$o.id] // null) as $x
          | if $x == null or ($o.status == "written" and $x.status == "exists") then $o else $x end]
        + [$n[0][] | select(.id as $i | $oldIds | index($i) | not)])})}' \
    | node "$WRITE_STATE" "$STATE" >/dev/null || echo "  WARN: could not record the writes in $STATE" >&2
fi
exit "$RC"
