#!/usr/bin/env bash
# Interactive TUI to push the OpenKotOR/wiki clone to:
#   - origin  → https://github.com/OpenKotOR/wiki.git
#   - website-wiki → https://github.com/OpenKotOR/website.wiki (mirror; needs wiki initialized in GitHub UI first)
# Run from anywhere; resolves repo root automatically.

# -u and failed git push would abort the TUI; use a relaxed mode for the menu loop
set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT" || { echo "Cannot cd to $REPO_ROOT" >&2; exit 1; }

WEBSITE_WIKI_REMOTE="website-wiki"
WEBSITE_WIKI_URL="https://github.com/OpenKotOR/website.wiki.git"
ORIGIN_EXPECT="OpenKotOR/wiki"

# --- colors (no-op if not a tty) ---
if [ -t 1 ]; then
  BOLD="\e[1m"
  DIM="\e[2m"
  RED="\e[31m"
  GREEN="\e[32m"
  YEL="\e[33m"
  CYAN="\e[36m"
  RST="\e[0m"
else
  BOLD=""; DIM=""; RED=""; GREEN=""; YEL=""; CYAN=""; RST=""
fi

print_banner() {
  echo -e "${BOLD}OpenKotOR wiki — push to remotes${RST}"
  echo -e "${DIM}Repository: $REPO_ROOT${RST}"
  echo ""
}

warn_first_wiki() {
  echo -e "${YEL}Note:${RST} Pushing to ${WEBSITE_WIKI_REMOTE} fails with \"Repository not found\" until someone"
  echo "  creates the first page at: https://github.com/OpenKotOR/website/wiki"
  echo ""
}

ensure_git_repo() {
  if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "Not a git repository: $REPO_ROOT" >&2
    exit 1
  fi
}

check_origin() {
  local o
  o=$(git remote get-url origin 2>/dev/null || true)
  if [[ -z "$o" ]]; then
    echo -e "${RED}No 'origin' remote. Add it or clone from OpenKotOR/wiki.${RST}" >&2
  elif ! echo "$o" | tr '[:upper:]' '[:lower:]' | grep -qE 'openkotor/wiki'; then
    echo -e "${YEL}Warning:${RST} origin does not look like $ORIGIN_EXPECT ($o)"
  fi
}

get_branch() {
  git rev-parse --abbrev-ref HEAD
}

do_status() {
  echo -e "${BOLD}— Status —${RST}"
  check_origin
  echo "Branch: $(get_branch)"
  echo ""
  echo "Remotes:"
  git remote -v | sed 's/^/  /'
  echo ""
  if ! git diff-index --quiet HEAD -- 2>/dev/null; then
    echo -e "${YEL}Uncommitted changes:${RST}"
    git status -sb
  else
    echo -e "${GREEN}Working tree clean (no uncommitted changes).${RST}"
  fi
  echo ""
  echo "Latest commit:"
  git log -1 --oneline --decorate
  echo ""
}

read_yes() {
  local def="${1:-y}"; shift
  local prompt="${*:-Continue?}" r hint
  if [[ "$def" == "y" || "$def" == "Y" ]]; then hint="Y/n"; else hint="y/N"; fi
  read -r -p "$prompt [$hint] " r || return 1
  r="${r:-$def}"
  [[ "$r" =~ ^[yY] ]]
}

add_website_wiki_remote() {
  if git remote get-url "$WEBSITE_WIKI_REMOTE" &>/dev/null; then
    echo "Remote '$WEBSITE_WIKI_REMOTE' already: $(git remote get-url $WEBSITE_WIKI_REMOTE)"
    return 0
  fi
  echo "Adding remote $WEBSITE_WIKI_REMOTE -> $WEBSITE_WIKI_URL"
  git remote add "$WEBSITE_WIKI_REMOTE" "$WEBSITE_WIKI_URL"
}

push_origin() {
  local br
  br="$(get_branch)"
  if [[ "$br" != "main" ]]; then
    if ! read_yes n "Branch is '$br', not 'main'. Push it to origin anyway?"; then
      return 0
    fi
  fi
  echo "Running: git push -u origin \"$br\""
  if ! read_yes n "Confirm push to origin?"; then
    return 0
  fi
  if ! git push -u origin "$br"; then
    echo -e "${RED}git push to origin failed.${RST}" >&2
    return 0
  fi
  echo -e "${GREEN}Pushed to origin.$RST"
}

push_website_wiki() {
  warn_first_wiki
  add_website_wiki_remote
  if ! read_yes n "Mirror with --force to $WEBSITE_WIKI_REMOTE? (overwrites that wiki remote branch)"; then
    return 0
  fi
  echo "Trying: git push $WEBSITE_WIKI_REMOTE main:main --force"
  if ! git push "$WEBSITE_WIKI_REMOTE" main:main --force; then
    echo "Retrying: main:master"
    if ! git push "$WEBSITE_WIKI_REMOTE" main:master --force; then
      echo -e "${RED}git push to $WEBSITE_WIKI_REMOTE failed.${RST}" >&2
      return 0
    fi
  fi
  echo -e "${GREEN}Pushed to $WEBSITE_WIKI_REMOTE. Open https://github.com/OpenKotOR/website/wiki${RST}"
}

push_both() {
  do_status
  push_origin
  echo ""
  push_website_wiki
}

main_menu() {
  while true; do
    clear 2>/dev/null || true
    print_banner
    current_branch
    echo -e "${DIM}────────────────────────────${RST}"
    echo "  1) Show status (branch, remotes, uncommitted, ahead/behind)"
    echo "  2) Push current branch to ${BOLD}origin${RST}  (github.com/OpenKotOR/${BOLD}wiki${RST})"
    echo "  3) Add $WEBSITE_WIKI_REMOTE remote (if missing)"
    echo "  4) Push ${BOLD}main${RST} to ${BOLD}website.wiki${RST} (mirror, uses --force)"
    echo "  5) Push to ${BOLD}origin${RST} then to ${BOLD}website.wiki${RST} (2 + 4)"
    echo "  6) Show help (first-wiki, URLs)"
    echo "  0) Exit"
    echo -e "${DIM}────────────────────────────${RST}"
    read -r -p "Choice [0-6]: " choice
    case "$choice" in
      1) do_status; read -r -p "Press Enter..." _ ;;
      2) push_origin; read -r -p "Press Enter..." _ ;;
      3) add_website_wiki_remote; read -r -p "Press Enter..." _ ;;
      4) push_website_wiki; read -r -p "Press Enter..." _ ;;
      5) push_both; read -r -p "Press Enter..." _ ;;
      6) help_text; read -r -p "Press Enter..." _ ;;
      0) echo "Bye."; exit 0 ;;
      *) echo "Invalid choice."; read -r -p "Press Enter..." _ ;;
    esac
  done
}

current_branch() {
  echo -e "  Current branch: ${CYAN}$(get_branch)${RST}"
  echo ""
}

help_text() {
  echo "origin       → the OpenKotOR/wiki GitHub repository (source of truth for Markdown)."
  echo "website.wiki → the GitHub Wiki attached to OpenKotOR/website. It is a separate"
  echo "                git URL ($WEBSITE_WIKI_URL)."
  echo "               Use --force when mirroring so the wiki matches this repo’s main."
  echo ""
  warn_first_wiki
  echo "Docs: see scripts/Mirror-Website-Wiki.ps1 and WIKI-LAYOUT.md in this repo."
}

# --- main ---
ensure_git_repo
# Optional: if argv --help
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  help_text
  exit 0
fi

# Git Bash on Windows: `clear` may be clear.exe
main_menu
