#!/usr/bin/env bash
# Initialize a PR draft file for a given issue number.
# Usage: init-pr-draft.sh <issue-number>
set -euo pipefail

die() {
  echo "init-pr-draft: $*" >&2
  exit 1
}

# Required argument.
ISSUE_NUMBER="${1:?issue number required}"

# Resolve repository root (works regardless of the current working directory).
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR=""
if command -v git >/dev/null 2>&1; then
  ROOT_DIR="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null || true)"
fi
if [ -z "$ROOT_DIR" ]; then
  ROOT_DIR="$(cd "$SCRIPT_DIR/../../../../" && pwd)"
fi
if [ ! -d "$ROOT_DIR" ]; then
  die "Unable to resolve repository root from ${SCRIPT_DIR}."
fi

# Template path and output location.
TEMPLATE="${ROOT_DIR}/.aiassistant/skills/issue-workflow/refs/pr-template.md"
OUT_DIR="${ROOT_DIR}/.TemporaryItems/Issues/imagify-plugin/pull"
OUT_FILE="${OUT_DIR}/${ISSUE_NUMBER}.md"

if [ ! -f "$TEMPLATE" ]; then
  die "Template not found: ${TEMPLATE}"
fi

# Ensure output directory exists and copy the template.
mkdir -p "$OUT_DIR"
cp "$TEMPLATE" "$OUT_FILE"

# Replace placeholder with the issue number.
sed -i "s/(issue number)/${ISSUE_NUMBER}/g" "$OUT_FILE"

# Print the path for downstream tooling.
echo "$OUT_FILE"
