#!/bin/sh
#
# git-issue-comment - Add a comment to an issue
#

set -e

. "$(dirname "$0")/git-issue-lib"

usage() {
	cat <<EOF
usage: git issue comment <issue-id> -m <message>

Options:
   -m, --message <text>   Comment text (required)
   -h, --help             Show this help
EOF
	exit 1
}

issue_prefix=""
message=""

# Parse the issue ID first (before options)
if test $# -gt 0
then
	case "$1" in
		-h|--help)
			usage
			;;
		-*)
			;;
		*)
			issue_prefix="$1"
			shift
			;;
	esac
fi

while test $# -gt 0
do
	case "$1" in
		-m|--message)
			test $# -ge 2 || { echo "error: -m requires a value" >&2; exit 1; }
			message="$2"
			shift 2
			;;
		-h|--help)
			usage
			;;
		--)
			shift
			break
			;;
		-*)
			echo "error: unknown option '$1'" >&2
			usage
			;;
		*)
			if test -z "$issue_prefix"
			then
				issue_prefix="$1"
			fi
			shift
			;;
	esac
done

if test -z "$issue_prefix"
then
	echo "error: issue ID is required" >&2
	usage
fi

if test -z "$message"
then
	echo "error: comment message is required (-m)" >&2
	usage
fi

# Validate no trailer injection via newlines
case "$message" in
	*"
"*)
		# Multi-line comments: reject lines that could be parsed as issue trailers
		if printf '%s\n' "$message" | grep -qE '^(State|Labels|Assignee|Priority|Milestone|Title|Provider-ID|Format-Version|Fixed-By|Release|Reason|Conflict): '
		then
			echo "error: comment contains lines that resemble issue metadata trailers" >&2
			echo "       (e.g., 'State: ...', 'Labels: ...', 'Priority: ...')" >&2
			echo "       this could corrupt issue metadata when queried" >&2
			exit 1
		fi
		;;
esac

# Verify we are inside a git repository
git rev-parse --git-dir >/dev/null 2>&1 || {
	echo "fatal: not a git repository" >&2
	exit 128
}

# Validate git identity before creating commits
validate_git_identity

# Resolve the issue ID
matches="$(resolve_issue "$issue_prefix")"
count="$(printf '%s\n' "$matches" | grep -c . || true)"

if test "$count" -eq 0
then
	echo "error: issue '$issue_prefix' not found" >&2
	exit 1
fi

if test "$count" -gt 1
then
	echo "error: ambiguous issue prefix '$issue_prefix'" >&2
	exit 1
fi

issue_ref="$matches"
uuid="${issue_ref#refs/issues/}"
short_id="$(printf '%s' "$uuid" | cut -c1-7)"

# Get current issue HEAD
issue_head="$(git rev-parse "$issue_ref")"

# Get the empty tree SHA
empty_tree="$(git hash-object -t tree /dev/null)"

if test -z "$empty_tree"
then
	printf 'error: failed to generate empty tree hash\n' >&2
	exit 128
fi

# Create the comment commit with the current HEAD as parent
tmpfile="$(mktemp)"
trap 'rm -f "$tmpfile"' EXIT

printf '%s\n' "$message" > "$tmpfile"

commit="$(git commit-tree -p "$issue_head" -- "$empty_tree" < "$tmpfile")"

# Update the ref with retry on concurrent modification
if ! update_ref_with_retry "$issue_ref" "$commit" "$issue_head"
then
	# Error already printed by update_ref_with_retry
	exit 1
fi

printf 'Added comment to %s\n' "$short_id"
