#!/usr/bin/env bash
# Execute ohpm publish in an interactive terminal so the user can enter
# their SSH key passphrase when prompted.
source "$(cd "$(dirname "$0")/.." && pwd)/scripts/_config.sh"

HAR="$REPO_ROOT/flexui-engine/output/flexui_engine.har"
if [ ! -f "$HAR" ]; then
  err "HAR not found: $HAR"
  err "请先执行 build.sh build-engine --release"
  exit 1
fi

log "Opening interactive terminal for ohpm publish..."
echo ""
echo "  HAR: $HAR"
echo ""
echo "  新窗口中会提示输入私钥密码,输入后完成发布。"
echo ""

case "$(uname -s)" in
  MINGW*|MSYS*|CYGWIN*)
    # Windows Git Bash — open PowerShell window (auto-executes command)
    HAR_WIN="$(echo "$HAR" | sed 's|\\|/|g; s|^\([A-Za-z]\):|/\1|')"
    # If path already starts with a drive letter like /d/..., convert to D:/
    if echo "$HAR_WIN" | grep -q '^/[a-zA-Z]/'; then
      HAR_WIN="$(echo "$HAR_WIN" | sed 's|^/\([a-zA-Z]\)/|\1:/|')"
    fi
    powershell -Command "Start-Process powershell -ArgumentList '-NoExit', '-Command', 'ohpm publish $HAR_WIN'"
    ;;
  Darwin)
    # macOS — open Terminal.app
    osascript -e "tell app \"Terminal\" to do script \"ohpm publish '$HAR'; echo ''; echo 'Press Ctrl+C to close...'; read\""
    ;;
  Linux)
    # Linux — open new terminal
    if command -v gnome-terminal &>/dev/null; then
      gnome-terminal -- bash -c "ohpm publish '$HAR'; read -p 'Press Enter to close...'"
    elif command -v xterm &>/dev/null; then
      xterm -e "ohpm publish '$HAR'; read -p 'Press Enter to close...'"
    else
      # Fallback: run inline
      warn "未找到终端模拟器,直接执行 ohpm publish..."
      ohpm publish "$HAR"
    fi
    ;;
  *)
    warn "未知平台,直接执行 ohpm publish..."
    ohpm publish "$HAR"
    ;;
esac