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

BASE_URL="${QIA_TAN_BASE_URL:-https://qiatan.fyi/api/tui}"
VERSION="${VERSION:-latest}"

# ---------------------------------------------------------------------------
# Detect OS + arch -> asset name (must match the R2 release layout)
# ---------------------------------------------------------------------------
uname_os() {
  case "$(uname -s)" in
    Linux*)  echo "unknown-linux-gnu" ;;
    Darwin*) echo "apple-darwin" ;;
    MINGW*|MSYS*|CYGWIN*|Windows*) echo "pc-windows-msvc" ;;
    *)       echo "unknown" ;;
  esac
}

uname_arch() {
  case "$(uname -m)" in
    x86_64|amd64) echo "x86_64" ;;
    arm64|aarch64) echo "aarch64" ;;
    *) echo "unknown" ;;
  esac
}

OS="$(uname_os)"
ARCH="$(uname_arch)"
if [ "$OS" = "unknown" ] || [ "$ARCH" = "unknown" ]; then
  echo "Unsupported platform: $(uname -s) $(uname -m)" >&2
  echo "Available prebuilt binaries:" >&2
  echo "  - x86_64 Linux" >&2
  echo "  - x86_64 + aarch64 macOS" >&2
  echo "  - x86_64 Windows" >&2
  exit 1
fi

TARGET="$ARCH-$OS"
EXT="tar.gz"
[ "$OS" = "pc-windows-msvc" ] && EXT="zip"
ASSET="qiatan-$TARGET.$EXT"

# `latest` resolves to the current version dir by asking the server for the
# version string (returned as plain text), then building the full asset URL.
if [ "$VERSION" = "latest" ]; then
  VERSION="$(curl -fsSL "$BASE_URL/latest")"
fi
URL="$BASE_URL/$VERSION/$ASSET"

# ---------------------------------------------------------------------------
# Install location
# ---------------------------------------------------------------------------
INSTALL_DIR="${QIA_TAN_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$INSTALL_DIR"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

echo "Downloading qiatan ($TARGET)…"
curl -fsSL "$URL" -o "$TMP/$ASSET"

echo "Extracting…"
case "$EXT" in
  tar.gz) tar -xzf "$TMP/$ASSET" -C "$TMP" ;;
  zip)    unzip -oq "$TMP/$ASSET" -d "$TMP" ;;
esac

EXE_NAME="qiatan"
[ "$OS" = "pc-windows-msvc" ] && EXE_NAME="qiatan.exe"
BIN="$TMP/$EXE_NAME"

chmod +x "$BIN" 2>/dev/null || true
if mv -f "$BIN" "$INSTALL_DIR/$EXE_NAME"; then
  echo "Installed qiatan to $INSTALL_DIR/$EXE_NAME"
else
  echo "Install failed." >&2
  exit 1
fi

echo ""

# ---------------------------------------------------------------------------
# PATH
#
# Offer to write the export into the shell profile rather than printing a line
# and hoping. Piped into bash, stdin is the script itself, so the prompt has to
# read from the terminal directly; where there is no terminal (CI) we fall back
# to printing the instruction.
#
#   QIA_TAN_ADD_PATH=1  add without asking
#   QIA_TAN_ADD_PATH=0  never touch the profile
# ---------------------------------------------------------------------------
case ":$PATH:" in
  *":$INSTALL_DIR:"*)
    echo "Already on your PATH. Run: qiatan"
    exit 0
    ;;
esac

# Pick the profile the user's login shell actually reads.
case "$(basename "${SHELL:-}")" in
  zsh)  PROFILE="$HOME/.zshrc" ;;
  bash) if [ -f "$HOME/.bashrc" ]; then PROFILE="$HOME/.bashrc"; else PROFILE="$HOME/.bash_profile"; fi ;;
  *)    PROFILE="$HOME/.profile" ;;
esac

ANSWER="${QIA_TAN_ADD_PATH:-}"
if [ -z "$ANSWER" ]; then
  if [ -r /dev/tty ]; then
    printf "Add %s to your PATH in %s? [Y/n] " "$INSTALL_DIR" "$PROFILE" > /dev/tty
    read -r REPLY < /dev/tty || REPLY=""
    case "$REPLY" in
      [nN]*) ANSWER=0 ;;
      *)     ANSWER=1 ;;
    esac
  else
    ANSWER=0
  fi
fi

if [ "$ANSWER" = "1" ]; then
  # Marker keeps a re-run from stacking duplicate exports.
  MARKER="# added by qiatan installer"
  if ! grep -qF "$MARKER" "$PROFILE" 2>/dev/null; then
    {
      echo ""
      echo "$MARKER"
      echo "export PATH=\"$INSTALL_DIR:\$PATH\""
    } >> "$PROFILE"
  fi
  echo "Added $INSTALL_DIR to $PROFILE."
  echo "Open a new terminal (or: source $PROFILE), then run: qiatan"
else
  echo "Add it to your PATH, then run: qiatan"
  echo "  export PATH=\"$INSTALL_DIR:\$PATH\"  # add to $PROFILE"
fi

# Git Bash installs under the MSYS home, which Windows itself never searches, so
# the binary stays invisible to PowerShell and cmd. Point at the native script.
if [ "$OS" = "pc-windows-msvc" ]; then
  echo ""
  echo "For PowerShell, install with:"
  echo "  irm https://qiatan.fyi/api/tui/install.ps1 | iex"
fi
