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

# MIDAS CLI installer
#   curl -fsSL https://get.trymidas.io | bash

APP=midas
BASE_URL="${MIDAS_INSTALL_BASE:-https://get.trymidas.io}"
INSTALL_DIR="${MIDAS_INSTALL_DIR:-$HOME/.midas/bin}"

BOLD='\033[1m'
DIM='\033[0;2m'
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

err() { echo -e "${RED}error:${NC} $*" >&2; exit 1; }
info() { echo -e "${DIM}$*${NC}"; }

command -v curl >/dev/null 2>&1 || err "curl is required but not installed."

raw_os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$raw_os" in
  darwin) os=darwin ;;
  linux)  os=linux ;;
  msys*|mingw*|cygwin*|windows*) err "Windows isn't supported by this script. Ask for the Windows build directly." ;;
  *) err "unsupported OS: $raw_os" ;;
esac

raw_arch=$(uname -m)
case "$raw_arch" in
  arm64|aarch64) arch=arm64 ;;
  x86_64|amd64)  arch=x64 ;;
  *) err "unsupported architecture: $raw_arch" ;;
esac

target="${APP}-${os}-${arch}"
url="${BASE_URL}/bin/${target}"

echo -e "${BOLD}Installing MIDAS CLI${NC} ${DIM}(${os}-${arch})${NC}"

version=$(curl -fsSL "${BASE_URL}/VERSION" 2>/dev/null || true)
[ -n "$version" ] && info "version ${version}"

tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

info "downloading ${url}"
if ! curl -fSL --proto '=https' --tlsv1.2 -o "$tmp" "$url"; then
  err "download failed. No build for ${target} yet — ask for it to be published."
fi

# A truncated or HTML error page is not a Mach-O/ELF binary; guard against it.
if [ ! -s "$tmp" ]; then
  err "downloaded file is empty."
fi

mkdir -p "$INSTALL_DIR"
mv "$tmp" "$INSTALL_DIR/${APP}"
chmod 755 "$INSTALL_DIR/${APP}"
trap - EXIT

echo -e "${GREEN}installed${NC} ${INSTALL_DIR}/${APP}"

# ---- ensure INSTALL_DIR is on PATH ----------------------------------------
add_path_line="export PATH=\"${INSTALL_DIR}:\$PATH\""
marker="# midas cli"

already_on_path=false
case ":$PATH:" in
  *":${INSTALL_DIR}:"*) already_on_path=true ;;
esac

rc=""
case "${SHELL:-}" in
  */zsh)  rc="$HOME/.zshrc" ;;
  */bash) if [ "$os" = darwin ]; then rc="$HOME/.bash_profile"; else rc="$HOME/.bashrc"; fi ;;
esac

if [ "$already_on_path" = true ]; then
  : # nothing to do
elif [ -n "$rc" ]; then
  if [ -f "$rc" ] && grep -qF "$marker" "$rc"; then
    :
  else
    printf '\n%s\n%s\n' "$marker" "$add_path_line" >> "$rc"
    info "added ${INSTALL_DIR} to PATH in ${rc}"
  fi
  needs_reload=true
else
  echo -e "${YELLOW}note:${NC} add this to your shell config to put midas on PATH:"
  echo -e "  ${add_path_line}"
fi

echo ""
echo -e "${BOLD}Done.${NC} Next steps:"
if [ "${needs_reload:-false}" = true ] && [ "$already_on_path" != true ]; then
  echo -e "  1. Restart your terminal (or run: ${BOLD}source ${rc}${NC})"
  echo -e "  2. Run ${BOLD}midas${NC}"
else
  echo -e "  1. Run ${BOLD}midas${NC}"
fi
echo -e "  ${DIM}·${NC} Inside midas, type ${BOLD}/login${NC} to connect your MIDAS account."
echo -e "  ${DIM}·${NC} MIDAS routes your work across models automatically — just start coding."
