#!/usr/bin/env bash
# Lumo CLI + Skill installer for Linux and macOS.
#
# Usage: extract the release bundle (LumoCLI-<os>-<arch>.tar.gz) and run:
#          ./install.sh
#
# Flags:
#   --no-skill                         skip skill installation
#   --skill-target auto|all|claude|codex|opencode|cursor|claude,codex,cursor
set -euo pipefail

INSTALL_SKILL=true
SKILL_TARGET="auto"
while [ "$#" -gt 0 ]; do
  case "$1" in
    --no-skill)
      INSTALL_SKILL=false
      ;;
    --skill-target)
      shift
      if [ "$#" -eq 0 ]; then
        echo "Error: --skill-target requires a value: auto, all, claude, codex, opencode, cursor, or a comma-separated combination" >&2
        exit 1
      fi
      SKILL_TARGET="$1"
      ;;
    --skill-target=*)
      SKILL_TARGET="${1#*=}"
      ;;
    *)
      echo "Error: unknown flag: $1" >&2
      exit 1
      ;;
  esac
  shift
done

# ─── Detect platform ────────────────────────────────────────────────────────

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case "$OS" in
  linux)  OS="linux" ;;
  darwin) OS="darwin" ;;
  *)      echo "Error: unsupported OS: $OS" >&2; exit 1 ;;
esac

case "$ARCH" in
  x86_64|amd64)  ARCH="amd64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  *)             echo "Error: unsupported architecture: $ARCH" >&2; exit 1 ;;
esac

echo ""
echo "  Lumo CLI Installer"
echo "  Platform: ${OS}/${ARCH}"
echo ""

# ─── Locate bundle files ────────────────────────────────────────────────────

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)" || SCRIPT_DIR=""
LOCAL_BINARY=""
BUNDLE_DIR=""

# Binary may be next to script or in parent dir (goreleaser puts scripts/ in subfolder)
for dir in "$SCRIPT_DIR" "${SCRIPT_DIR%/*}"; do
  [ -z "$dir" ] && continue
  if [ -f "$dir/lumo" ]; then
    LOCAL_BINARY="$dir/lumo"
    BUNDLE_DIR="$dir"
    break
  fi
done

if [ -z "$LOCAL_BINARY" ]; then
  echo "Error: binary 'lumo' not found next to install.sh or in its parent directory." >&2
  echo "" >&2
  echo "This installer only works from an extracted release bundle." >&2
  echo "Download LumoCLI-${OS}-${ARCH}.tar.gz from:" >&2
  echo "  https://gitlab.horusdev.com.br/horus/lumo-cli/-/releases" >&2
  echo "then extract it and run ./install.sh from inside the extracted folder." >&2
  exit 1
fi

LOCAL_SKILL_DIR=""
if [ -f "$BUNDLE_DIR/skill/SKILL.md" ]; then
  LOCAL_SKILL_DIR="$BUNDLE_DIR/skill"
fi

LOCAL_SKILL_DESIGN_DIR=""
if [ -f "$BUNDLE_DIR/skill-design/SKILL.md" ]; then
  LOCAL_SKILL_DESIGN_DIR="$BUNDLE_DIR/skill-design"
fi

LOCAL_SKILL_DECKS_DIR=""
if [ -f "$BUNDLE_DIR/skill-decks/SKILL.md" ]; then
  LOCAL_SKILL_DECKS_DIR="$BUNDLE_DIR/skill-decks"
fi

LOCAL_SKILL_SCOPE_DIR=""
if [ -f "$BUNDLE_DIR/skill-scope/SKILL.md" ]; then
  LOCAL_SKILL_SCOPE_DIR="$BUNDLE_DIR/skill-scope"
fi

LOCAL_SKILL_MOCKUP_DIR=""
if [ -f "$BUNDLE_DIR/skill-mockup/SKILL.md" ]; then
  LOCAL_SKILL_MOCKUP_DIR="$BUNDLE_DIR/skill-mockup"
fi

# ─── Install binary ─────────────────────────────────────────────────────────

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
cp "$LOCAL_BINARY" "$TMP/lumo"
chmod +x "$TMP/lumo"

INSTALL_DIR=""
if [ -w "/usr/local/bin" ]; then
  INSTALL_DIR="/usr/local/bin"
  cp "$TMP/lumo" "$INSTALL_DIR/lumo"
elif command -v sudo &>/dev/null; then
  INSTALL_DIR="/usr/local/bin"
  echo "  Installing to $INSTALL_DIR (requires sudo)..."
  sudo cp "$TMP/lumo" "$INSTALL_DIR/lumo"
  sudo chmod +x "$INSTALL_DIR/lumo"
else
  INSTALL_DIR="$HOME/.local/bin"
  mkdir -p "$INSTALL_DIR"
  cp "$TMP/lumo" "$INSTALL_DIR/lumo"
  chmod +x "$INSTALL_DIR/lumo"

  if ! echo "$PATH" | tr ':' '\n' | grep -qx "$INSTALL_DIR"; then
    SHELL_NAME=$(basename "$SHELL")
    case "$SHELL_NAME" in
      zsh)  RC="$HOME/.zshrc" ;;
      bash) RC="$HOME/.bashrc" ;;
      *)    RC="$HOME/.profile" ;;
    esac
    echo "export PATH=\"\$HOME/.local/bin:\$PATH\"" >> "$RC"
    echo "  Added $INSTALL_DIR to PATH in $RC"
    echo "  Run 'source $RC' or open a new terminal"
  fi
fi

echo "  CLI installed: $INSTALL_DIR/lumo"

# ─── Remove stray copies on PATH (avoid v1+v2 coexistence) ─────────────
# If the user installed a previous version manually (homebrew, custom
# path, etc.), we'd leave both binaries on disk and let PATH order
# decide which one runs - confusing and non-deterministic. Walk the
# PATH and remove any other `lumo` we find, leaving only ours.
TARGET_REAL="$(readlink -f "$INSTALL_DIR/lumo" 2>/dev/null || echo "$INSTALL_DIR/lumo")"
IFS=':' read -ra PATH_PARTS <<< "$PATH"
for p in "${PATH_PARTS[@]}"; do
  [ -z "$p" ] && continue
  candidate="$p/lumo"
  [ ! -e "$candidate" ] && continue
  candidate_real="$(readlink -f "$candidate" 2>/dev/null || echo "$candidate")"
  # Skip the symlink we may have just placed.
  if [ "$candidate_real" = "$TARGET_REAL" ]; then
    continue
  fi
  echo "  Removing stale binary at $candidate (was: $candidate_real)"
  if [ -w "$candidate" ] || [ -w "$p" ]; then
    rm -f "$candidate"
  elif command -v sudo &>/dev/null; then
    sudo rm -f "$candidate"
  else
    echo "  Warning: could not remove $candidate - please remove manually." >&2
  fi
done

# Sanity: which lumo now resolves to?
RESOLVED="$(command -v lumo 2>/dev/null || true)"
RESOLVED_REAL="$(readlink -f "$RESOLVED" 2>/dev/null || echo "$RESOLVED")"
if [ -n "$RESOLVED" ] && [ "$RESOLVED_REAL" != "$TARGET_REAL" ]; then
  echo "  Warning: 'lumo' on PATH still resolves to $RESOLVED" >&2
  echo "  This may be a shim from your shell - open a new terminal." >&2
fi

# ─── Install skill ──────────────────────────────────────────────────────────

agent_installed() {
  case "$1" in
    claude)
      command -v claude >/dev/null 2>&1 || [ -d "$HOME/.claude" ]
      ;;
    codex)
      command -v codex >/dev/null 2>&1 || [ -d "$HOME/.codex" ] || [ -d "$HOME/.agents" ]
      ;;
    opencode)
      command -v opencode >/dev/null 2>&1 || [ -d "$HOME/.config/opencode" ]
      ;;
    cursor)
      command -v cursor >/dev/null 2>&1 || command -v cursor-agent >/dev/null 2>&1 || [ -d "$HOME/.cursor" ]
      ;;
    *)
      return 1
      ;;
  esac
}

install_skill_to() {
  local agent_name="$1"
  local skill_dir="$2"

  # Legacy cleanup - older installs wrote to .../skills/lumo (no -cli
  # suffix). If both names exist, the agent loads two skills with
  # conflicting content; sweep the legacy path first.
  local legacy_dir="${skill_dir%lumo-cli}lumo"
  if [ "$legacy_dir" != "$skill_dir" ] && [ -e "$legacy_dir" ]; then
    rm -rf "$legacy_dir"
  fi

  rm -rf "$skill_dir"
  mkdir -p "$skill_dir"
  cp "$LOCAL_SKILL_DIR/SKILL.md" "$skill_dir/"
  if [ -d "$LOCAL_SKILL_DIR/references" ]; then
    cp -r "$LOCAL_SKILL_DIR/references" "$skill_dir/"
  fi
  echo "  Skill installed ($agent_name): $skill_dir"

  # Install lumo-design skill when present in bundle (absent in old bundles).
  if [ -n "$LOCAL_SKILL_DESIGN_DIR" ]; then
    local design_dir="${skill_dir%lumo-cli}lumo-design"
    rm -rf "$design_dir"
    mkdir -p "$design_dir"
    cp "$LOCAL_SKILL_DESIGN_DIR/SKILL.md" "$design_dir/"
    if [ -d "$LOCAL_SKILL_DESIGN_DIR/references" ]; then
      cp -r "$LOCAL_SKILL_DESIGN_DIR/references" "$design_dir/"
    fi
    echo "  Skill installed ($agent_name): $design_dir"
  fi

  # Install lumo-decks skill when present in bundle (absent in old bundles).
  if [ -n "$LOCAL_SKILL_DECKS_DIR" ]; then
    local decks_dir="${skill_dir%lumo-cli}lumo-decks"
    rm -rf "$decks_dir"
    mkdir -p "$decks_dir"
    cp -r "$LOCAL_SKILL_DECKS_DIR/." "$decks_dir/"
    echo "  Skill installed ($agent_name): $decks_dir"
  fi

  # Install lumo-scope skill when present in bundle (absent in old bundles).
  if [ -n "$LOCAL_SKILL_SCOPE_DIR" ]; then
    local scope_dir="${skill_dir%lumo-cli}lumo-scope"
    rm -rf "$scope_dir"
    mkdir -p "$scope_dir"
    cp -r "$LOCAL_SKILL_SCOPE_DIR/." "$scope_dir/"
    echo "  Skill installed ($agent_name): $scope_dir"
  fi

  # Install lumo-mockup skill when present in bundle (absent in old bundles).
  if [ -n "$LOCAL_SKILL_MOCKUP_DIR" ]; then
    local mockup_dir="${skill_dir%lumo-cli}lumo-mockup"
    rm -rf "$mockup_dir"
    mkdir -p "$mockup_dir"
    cp -r "$LOCAL_SKILL_MOCKUP_DIR/." "$mockup_dir/"
    echo "  Skill installed ($agent_name): $mockup_dir"
  fi
}

resolve_skill_targets() {
  case "$SKILL_TARGET" in
    auto)
      local covered=false
      if agent_installed claude; then echo "claude"; covered=true; fi
      if agent_installed codex; then echo "codex"; covered=true; fi
      if agent_installed opencode; then echo "opencode"; fi
      # Cursor reads ~/.claude/skills and ~/.agents/skills as compatibility
      # paths, so a user who already got the skill there would load it twice.
      # OpenCode does not count - Cursor never reads its skills dir.
      if [ "$covered" = false ] && agent_installed cursor; then echo "cursor"; fi
      ;;
    all)
      echo "claude"
      echo "codex"
      echo "opencode"
      echo "cursor"
      ;;
    *)
      echo "$SKILL_TARGET" | tr ',' '\n'
      ;;
  esac
  return 0
}

INSTALLED_SKILL_AGENTS=""
if [ "$INSTALL_SKILL" = true ]; then
  if [ -z "$LOCAL_SKILL_DIR" ]; then
    echo "  Skill not found in bundle (skill/SKILL.md missing) - skipping skill install." >&2
  else
    SKILL_TARGETS=$(resolve_skill_targets | awk 'NF && !seen[$0]++')
    if [ -z "$SKILL_TARGETS" ]; then
      echo "  No supported AI agent detected (Claude Code, Codex, OpenCode, or Cursor); skipping skill install." >&2
      echo "  Use --skill-target all to force installation to all known skill folders." >&2
    else
      while IFS= read -r target; do
        case "$target" in
          claude)
            install_skill_to "Claude Code" "$HOME/.claude/skills/lumo-cli"
            INSTALLED_SKILL_AGENTS="${INSTALLED_SKILL_AGENTS:+$INSTALLED_SKILL_AGENTS, }Claude Code"
            ;;
          codex)
            install_skill_to "Codex" "$HOME/.agents/skills/lumo-cli"
            INSTALLED_SKILL_AGENTS="${INSTALLED_SKILL_AGENTS:+$INSTALLED_SKILL_AGENTS, }Codex"
            ;;
          opencode)
            install_skill_to "OpenCode" "$HOME/.config/opencode/skills/lumo-cli"
            INSTALLED_SKILL_AGENTS="${INSTALLED_SKILL_AGENTS:+$INSTALLED_SKILL_AGENTS, }OpenCode"
            ;;
          cursor)
            install_skill_to "Cursor" "$HOME/.cursor/skills/lumo-cli"
            INSTALLED_SKILL_AGENTS="${INSTALLED_SKILL_AGENTS:+$INSTALLED_SKILL_AGENTS, }Cursor"
            ;;
          "")
            ;;
          *)
            echo "  Unknown skill target '$target' - supported: auto, all, claude, codex, opencode, cursor." >&2
            exit 1
            ;;
        esac
      done <<< "$SKILL_TARGETS"
    fi
  fi
fi

# ─── Done ────────────────────────────────────────────────────────────────────

VERSION=$("$INSTALL_DIR/lumo" version 2>/dev/null | head -1) || true

echo ""
echo "  Done! Lumo CLI${VERSION:+ $VERSION} is ready."
echo ""
echo "  Next steps:"
echo "    lumo auth login         # authenticate"
echo "    lumo auth status        # check connection"
if [ -n "$INSTALLED_SKILL_AGENTS" ]; then
  echo "    restart ${INSTALLED_SKILL_AGENTS} to load the updated skill"
fi
echo ""
