#!/data/data/com.termux/files/usr/bin/bash
# zyvo-uninstall — cleanly removes ZYVO from the device
#
# Usage:
#   zyvo uninstall          (asks for confirmation)
#   zyvo uninstall -y       (skip confirmation)
#
# Removes:
#   - the zyvo / oc-settings / zyvo-menu launchers
#   - the ZYVO layer (config, skills, commands) at ~/.config/opencode
#   - the branded core binary at libexec + native libs
#   - PATH + OPENCODE_API_KEY lines from ~/.bashrc
#
# Keeps (never touched):
#   - your projects / session folders (/storage/emulated/0/zyvo)
#   - the opencode core install at ~/.opencode (separate tool)
set -e

PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"
HOME_DIR="${HOME:-/data/data/com.termux/files/home}"
CONFIG_DIR="$HOME/.config/opencode"
BIN_DIR=""
LIBEXEC_DIR=""
LIB_DIR=""

# resolve install layout (Termux vs ~/.local)
if [ -n "$PREFIX" ] && [ -d "$PREFIX" ] && [ -n "$(command -v pkg 2>/dev/null || true)" ]; then
    BIN_DIR="$PREFIX/bin"
    LIBEXEC_DIR="$PREFIX/libexec/opencode"
    LIB_DIR="$PREFIX/lib"
else
    BIN_DIR="$HOME/.local/bin"
    LIBEXEC_DIR="$HOME/.local/libexec/zyvo"
    LIB_DIR="$HOME/.local/lib/zyvo"
fi

if [ "${1:-}" != "-y" ] && [ "${1:-}" != "--yes" ]; then
    echo "This will remove ZYVO (AI coding CLI) from this device."
    echo "  launchers:  $BIN_DIR/{zyvo,zyvo-menu,oc-settings}"
    echo "  config:     $CONFIG_DIR  (opencode.json, agent, commands, skills)"
    echo "  core:       $LIBEXEC_DIR + $LIB_DIR"
    echo
    echo "Your projects and session folders are NOT touched."
    echo -n "Continue? [y/N]: "
    read -r CONFIRM || CONFIRM=""
    case "$CONFIRM" in
        y|Y|yes|YES) ;;
        *) echo "Aborted."; exit 1;;
    esac
fi

rm -f "$BIN_DIR/zyvo" "$BIN_DIR/zyvo-menu" "$BIN_DIR/oc-settings"
rm -f "$LIBEXEC_DIR/opencode.bin" "$LIBEXEC_DIR/zyvo-core-version"
rm -rf "$LIBEXEC_DIR" "$LIB_DIR"
rm -rf "$CONFIG_DIR"
echo "  ✓ launchers removed"
echo "  ✓ config layer removed ($CONFIG_DIR)"
echo "  ✓ core removed"

# clean ~/.bashrc additions (only the ZYVO lines)
RC="$HOME_DIR/.bashrc"
[ -f "$RC" ] || RC="$HOME_DIR/.profile"
if [ -f "$RC" ]; then
    grep -v "ZYVO AI\|ZYVO PATH\|OPENCODE_API_KEY=" "$RC" > "$RC.zyvo-clean" 2>/dev/null || true
    mv "$RC.zyvo-clean" "$RC"
    echo "  ✓ PATH + API key lines removed from $(basename "$RC")"
fi

echo
echo "ZYVO uninstalled. Your projects are still at /storage/emulated/0/zyvo."
echo "Reinstall any time with:  curl -fsSL https://raw.githubusercontent.com/zyvo9/zyvo/main/install.sh | bash"