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

usage() {
  cat >&2 <<'USAGE'
Usage:
  render-docx.sh <input.md>

Renders only the Discovery Project Document or Commercial Offer Markdown to a sibling .docx file.
USAGE
}

fail() {
  echo "render-docx: $*" >&2
  exit 1
}

display_path() {
  local path="$1"
  if command -v cygpath >/dev/null 2>&1; then
    cygpath -w "$path" 2>/dev/null || printf '%s' "$path"
  else
    printf '%s' "$path"
  fi
}

# --- pandoc bootstrap -------------------------------------------------------
# Ensure pandoc is available. If it is not on PATH, silently download the
# official standalone pandoc binary into a per-user cache and use it from
# there — no prompts, no messages, no questions. Works on Linux, macOS and
# Windows (Git Bash). Only a genuine install failure is reported, because a
# DOCX cannot be produced without pandoc.

pandoc_cache_dir() {
  printf '%s/the-ai-machine/pandoc/bin' "${XDG_CACHE_HOME:-$HOME/.cache}"
}

pandoc_dl_stdout() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$1"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO - "$1"
  else
    return 1
  fi
}

pandoc_dl_file() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -o "$2" "$1"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$2" "$1"
  else
    return 1
  fi
}

pandoc_asset_pattern() {
  local os arch
  os="$(uname -s 2>/dev/null || echo unknown)"
  arch="$(uname -m 2>/dev/null || echo unknown)"
  case "$arch" in
    x86_64|amd64) arch=amd64 ;;
    arm64|aarch64) arch=arm64 ;;
  esac
  case "$os" in
    Linux*)  [ "$arch" = arm64 ] && echo 'linux-arm64\.tar\.gz' || echo 'linux-amd64\.tar\.gz' ;;
    Darwin*) [ "$arch" = arm64 ] && echo 'arm64-macOS\.zip'     || echo 'x86_64-macOS\.zip' ;;
    MINGW*|MSYS*|CYGWIN*|Windows_NT) echo 'windows-x86_64\.zip' ;;
    *) return 1 ;;
  esac
}

pandoc_extract() {
  case "$1" in
    *.tar.gz|*.tgz) tar -xzf "$1" -C "$2" ;;
    *.zip)
      if command -v unzip >/dev/null 2>&1; then
        unzip -q "$1" -d "$2"
      else
        tar -xf "$1" -C "$2"   # bsdtar (Win10+/macOS) can extract zip
      fi ;;
    *) return 1 ;;
  esac
}

pandoc_install() {
  local pattern url tmp archive bindir src
  pattern="$(pandoc_asset_pattern)" || return 1
  url="$(pandoc_dl_stdout 'https://api.github.com/repos/jgm/pandoc/releases/latest' \
        | grep -oE '"browser_download_url": *"[^"]+"' \
        | sed -E 's/.*"(https[^"]+)".*/\1/' \
        | grep -E "$pattern" | head -1)"
  [ -n "$url" ] || return 1
  tmp="$(mktemp -d 2>/dev/null)" || return 1
  archive="$tmp/${url##*/}"
  pandoc_dl_file "$url" "$archive" || { rm -rf "$tmp"; return 1; }
  pandoc_extract "$archive" "$tmp" || { rm -rf "$tmp"; return 1; }
  src="$(find "$tmp" -type f \( -name pandoc -o -name pandoc.exe \) 2>/dev/null | head -1)"
  [ -n "$src" ] || { rm -rf "$tmp"; return 1; }
  bindir="$(pandoc_cache_dir)"
  mkdir -p "$bindir" || { rm -rf "$tmp"; return 1; }
  cp "$src" "$bindir/$(basename "$src")" || { rm -rf "$tmp"; return 1; }
  chmod +x "$bindir/$(basename "$src")" 2>/dev/null || true
  rm -rf "$tmp"
}

ensure_pandoc() {
  command -v pandoc >/dev/null 2>&1 && return 0
  local bindir
  bindir="$(pandoc_cache_dir)"
  if [ -x "$bindir/pandoc" ] || [ -x "$bindir/pandoc.exe" ]; then
    PATH="$bindir:$PATH"; export PATH
    command -v pandoc >/dev/null 2>&1 && return 0
  fi
  pandoc_install >/dev/null 2>&1 || return 1
  PATH="$bindir:$PATH"; export PATH
  command -v pandoc >/dev/null 2>&1
}

if [[ $# -ne 1 ]]; then
  usage
  exit 64
fi

INPUT_ARG="$1"
[[ "$INPUT_ARG" != -* ]] || { usage; exit 64; }
[[ -f "$INPUT_ARG" ]] || fail "input file does not exist: $INPUT_ARG"

case "$INPUT_ARG" in
  *.md|*.MD|*.markdown|*.MARKDOWN|*.Markdown) ;;
  *) fail "input must be a .md or .markdown file: $INPUT_ARG" ;;
esac

ensure_pandoc || fail "pandoc was not found and could not be installed automatically."

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/.." && pwd -P)"
TEMPLATE_DIR="$PLUGIN_DIR/skills/render-docx/templates"

case "$INPUT_ARG" in
  */project-doc/project.md|*\\project-doc\\project.md)
    REFERENCE_DOC="$TEMPLATE_DIR/project-doc-reference.docx"
    ;;
  */commercial-offer/commercial-offer.md|*\\commercial-offer\\commercial-offer.md)
    REFERENCE_DOC="$TEMPLATE_DIR/commercial-offer-reference.docx"
    ;;
  *)
    fail "only project-doc/project.md and commercial-offer/commercial-offer.md can be rendered to DOCX in machine-discovery"
    ;;
esac

[[ -f "$REFERENCE_DOC" ]] || fail "missing style template: $REFERENCE_DOC"

INPUT_DIR="$(cd "$(dirname "$INPUT_ARG")" && pwd -P)"
INPUT_NAME="$(basename "$INPUT_ARG")"
INPUT_STEM="${INPUT_NAME%.*}"
OUTPUT_NAME="${INPUT_STEM}.docx"
OUTPUT_PATH="${INPUT_DIR}/${OUTPUT_NAME}"

if [[ -e "$OUTPUT_PATH" ]]; then
  fail "output already exists: $(display_path "$OUTPUT_PATH")"
fi

(
  cd "$INPUT_DIR"
  pandoc "$INPUT_NAME" \
    --from=markdown+smart+fenced_divs \
    --to=docx \
    --reference-doc="$REFERENCE_DOC" \
    --resource-path="$INPUT_DIR" \
    --output="$OUTPUT_NAME"
)

echo "DOCX generated: $(display_path "$OUTPUT_PATH")"
