#!/usr/bin/env bash
set -euo pipefail

# Post or update an MR comment with analysis results
# Required env: GITLAB_TOKEN, CI_API_V4_URL, CI_PROJECT_ID,
#   CI_MERGE_REQUEST_IID, FALLOW_COMMAND
# Optional env: CHANGED_SINCE, INPUT_ROOT (for scoping results to changed files)

if [ -z "${GITLAB_TOKEN:-}" ]; then
  echo "WARNING: GITLAB_TOKEN is required to create or update MR comments; CI_JOB_TOKEN is read-only for MR notes in the official GitLab API. Skipping MR summary comment."
  exit 0
fi
: "${CI_API_V4_URL:?CI_API_V4_URL is required}"
: "${CI_PROJECT_ID:?CI_PROJECT_ID is required}"
: "${CI_MERGE_REQUEST_IID:?CI_MERGE_REQUEST_IID is required}"

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=gitlab_common.sh
source "${SCRIPT_DIR}/gitlab_common.sh"

# Initialize two sidecar markers so downstream jobs always see definitive
# values. GitLab CI lacks an equivalent of $GITHUB_OUTPUT; these greppable
# text files serve the same role when added to `artifacts: paths:`.
# The Rust post adapter may overwrite `fallow-skip-reason.txt` for clean runs.
printf 'none\n' > fallow-skip-reason.txt
printf 'false\n' > fallow-dedup-lookup-failed.txt

render_with_fallow() {
  local format=$1
  local output=$2
  prepare_fallow_render_args "$format" || return 1
  case "${FALLOW_SUMMARY_SCOPE:-all}" in
    ""|all|diff)
      export FALLOW_SUMMARY_SCOPE="${FALLOW_SUMMARY_SCOPE:-all}"
      ;;
    *)
      echo "WARNING: Unsupported FALLOW_SUMMARY_SCOPE '${FALLOW_SUMMARY_SCOPE}', expected 'all' or 'diff'; using 'all'"
      export FALLOW_SUMMARY_SCOPE="all"
      ;;
  esac
  FALLOW_COMMENT_ID="${FALLOW_COMMENT_ID:-fallow-results}" fallow "${FALLOW_RENDER_ARGS[@]}" > "$output" 2> fallow-comment-stderr.log || true
  # Surface fallow's structured-error envelope before the marker check so the
  # CLI message lands in the GitLab job log rather than a generic warning.
  if jq -e '.error == true' "$output" > /dev/null 2>&1; then
    echo "WARNING: fallow render failed: $(jq -r '.message // "unknown error"' "$output")"
    return 1
  fi
  grep -q "^<!-- fallow-id: ${FALLOW_COMMENT_ID:-fallow-results} -->" "$output" \
    && grep -q "Generated by fallow\\." "$output"
}

if FALLOW_PR_COMMENT_ENVELOPE_FILE="fallow-mr-comment-envelope.json" \
   FALLOW_PR_DECISION_FILE="fallow-mr-decision.json" \
   FALLOW_PR_DETAILS_FILE="fallow-mr-details.json" \
   render_with_fallow pr-comment-gitlab fallow-mr-comment.md; then
  ENVELOPE_ARGS=()
  [ -f fallow-mr-comment-envelope.json ] && ENVELOPE_ARGS=(--envelope fallow-mr-comment-envelope.json)
  if ! fallow ci post-pr-comment \
      --provider gitlab \
      --mr "$CI_MERGE_REQUEST_IID" \
      --project-id "$CI_PROJECT_ID" \
      --api-url "$CI_API_V4_URL" \
      --body fallow-mr-comment.md \
      "${ENVELOPE_ARGS[@]}" \
      --marker-id "${FALLOW_COMMENT_ID:-fallow-results}" \
      > fallow-mr-comment-plan.json; then
    echo "WARNING: Failed to post MR comment"
    exit 0
  fi
  ACTION=$(jq -r '.action' fallow-mr-comment-plan.json)
  REASON=$(jq -r '.skip_reason // "none"' fallow-mr-comment-plan.json)
  if [ "$ACTION" = "skip" ]; then
    printf '%s\n' "$REASON" > fallow-skip-reason.txt
  fi
  echo "MR comment action: ${ACTION} (${REASON})"
  exit 0
fi

echo "WARNING: Failed to render typed MR comment"
exit 0
