#!/usr/bin/env bash
# new-page.sh
# Scaffold a new Confluence page draft from a template into the local drafts
# folder. The draft is storage-format XHTML, ready to fill and post.
#
# Usage:
#   bash scripts/new-page.sh <space> <title> [template]
#     space    : AVP, BASS, etc. (see confluence-page/references/space-keys.md)
#     title    : Page title; spaces become + in the storage path
#     template : hub | how-to | rfc | postmortem (default: hub)
#
# Writes to:
#   ~/Netcracker/Projects/NDO/knowledge/confluence/drafts/<SPACE>/<slug>.xml
#
# Exit: 0 on success, 1 on bad args, 2 on missing template.

set -eu

if [[ $# -lt 2 ]]; then
  echo "Usage: $0 <space> <title> [template]" >&2
  exit 1
fi

SPACE="$(echo "$1" | tr '[:lower:]' '[:upper:]')"
TITLE="$2"
TEMPLATE="${3:-hub}"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(dirname "$SCRIPT_DIR")"
TEMPLATE_FILE="$ROOT/templates/${TEMPLATE}.md"

if [[ ! -f "$TEMPLATE_FILE" ]]; then
  echo "Template not found: $TEMPLATE_FILE" >&2
  echo "Available templates:" >&2
  ls "$ROOT/templates" 2>/dev/null | sed 's/\.md$//' | sed 's/^/  - /' >&2
  exit 2
fi

DRAFT_ROOT="${DRAFT_ROOT:-$HOME/Netcracker/Projects/NDO/knowledge/confluence/drafts}"
DRAFT_DIR="$DRAFT_ROOT/$SPACE"
mkdir -p "$DRAFT_DIR"

SLUG="$(echo "$TITLE" | tr '[:upper:]' '[:lower:]' | tr ' /' '--' | tr -cd 'a-z0-9-_')"
DRAFT_FILE="$DRAFT_DIR/${SLUG}.xml"

{
  echo '<?xml version="1.0" encoding="UTF-8"?>'
  echo "<page xmlns:ac=\"http://atlassian.com/content\" xmlns:ri=\"http://atlassian.com/resource/identifier\">"
  echo "  <title>$TITLE</title>"
  echo "  <space>$SPACE</space>"
  echo "  <body>"
  echo "    <h1>$TITLE</h1>"
  echo "    <p><em>Drafted $(date -u +%Y-%m-%d). Edit the body below this line; the title and space are set above.</em></p>"
  echo ""
  echo "<!--"
  cat "$TEMPLATE_FILE"
  echo ""
  echo "-->"
  echo ""
  echo "    <p>Body starts here.</p>"
  echo ""
  echo "  </body>"
  echo "</page>"
} > "$DRAFT_FILE"

echo "Draft created: $DRAFT_FILE"
echo "Space:        $SPACE"
echo "Title:        $TITLE"
echo "Template:     $TEMPLATE"
echo
echo "Next:"
echo "  1. Fill the body between <body> and </body> using storage XHTML."
echo "  2. Run bash $SCRIPT_DIR/dry-run-publish.sh \"$DRAFT_FILE\""
echo "  3. Post via mcp-atlassian: confluence_create_page_from_file."
