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

# ── Cortex Installer ────────────────────────────────────────
# Usage:
#   curl -fsSL https://raw.githubusercontent.com/YOUR_USER/cortex/main/scripts/install.sh | sh
#   # or locally:
#   ./scripts/install.sh [--prefix ~/.local/bin]

REPO="cortex"
OWNER="shafiqul"  # Change to actual org/user
VERSION="${1:-latest}"
PREFIX="${PREFIX:-${HOME}/.cargo/bin}"
FORCE=false

# Colors
BOLD='\033[1m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

info()  { printf "${CYAN}  ╶ %s${NC}\n" "$1"; }
ok()    { printf "${GREEN}  ✓ %s${NC}\n" "$1"; }
warn()  { printf "${YELLOW}  ⚠ %s${NC}\n" "$1"; }
error() { printf "${RED}  ✗ %s${NC}\n" "$1"; exit 1; }

# ── Check prerequisites ─────────────────────────────────────
info "Checking prerequisites..."

if ! command -v cargo &>/dev/null; then
    warn "Rust/Cargo not found. Attempting to install Rust..."
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    source "${HOME}/.cargo/env"
    if ! command -v cargo &>/dev/null; then
        error "Failed to install Rust. Please install manually: https://rustup.rs"
    fi
    ok "Rust installed successfully"
else
    ok "Found cargo $(cargo --version | cut -d' ' -f2)"
fi

# ── Install from local source or GitHub ─────────────────────
if [ -f "Cargo.toml" ] && grep -q "name = \"cortex\"" Cargo.toml 2>/dev/null; then
    # Local install (running from repo root)
    info "Building from local source..."
    cargo build --release 2>&1 | tail -1
    BINARY="target/release/cortex"
else
    # Remote install — clone and build
    info "Cloning cortex repository..."
    TMP_DIR=$(mktemp -d)
    cd "$TMP_DIR"
    git clone --depth 1 "https://github.com/${OWNER}/${REPO}.git" 2>/dev/null || {
        # If git fails, try downloading release binary
        warn "Git not available, trying pre-built binary..."
        OS=$(uname -s | tr '[:upper:]' '[:lower:]')
        ARCH=$(uname -m)
        if [ "$ARCH" = "x86_64" ]; then ARCH="amd64"; fi
        RELEASE_URL="https://github.com/${OWNER}/${REPO}/releases/download/${VERSION}/cortex-${OS}-${ARCH}.tar.gz"
        if curl -fsSL "$RELEASE_URL" -o /tmp/cortex.tar.gz 2>/dev/null; then
            tar xzf /tmp/cortex.tar.gz -C /tmp/
            BINARY="/tmp/cortex"
        else
            error "Could not download release. Install Rust and run: cargo install cortex"
        fi
        cd - >/dev/null
    }
    if [ -f "Cargo.toml" ]; then
        info "Building from source..."
        cargo build --release 2>&1 | tail -1
        BINARY="target/release/cortex"
        cd - >/dev/null
    fi
fi

if [ ! -f "$BINARY" ]; then
    error "Build failed — binary not found at $BINARY"
fi
ok "Build complete"

# ── Install binary ──────────────────────────────────────────
install -d "$PREFIX" 2>/dev/null || true

# Try multiple locations
INSTALLED=false
for TARGET in "$PREFIX" "${HOME}/.local/bin" "${HOME}/.cargo/bin"; do
    if install -d "$TARGET" 2>/dev/null; then
        cp "$BINARY" "$TARGET/cortex"
        chmod +x "$TARGET/cortex"
        if [ "$(uname -s)" = "Linux" ]; then
            if command -v setcap &>/dev/null; then
                setcap cap_net_bind_service=+ep "$TARGET/cortex" 2>/dev/null || true
            fi
        fi
        INSTALLED=true
        # Add to PATH if needed
        SHELL_CONFIG=""
        case "${SHELL}" in
            */zsh) SHELL_CONFIG="${HOME}/.zshrc" ;;
            */bash) SHELL_CONFIG="${HOME}/.bashrc" ;;
        esac
        if [ -n "$SHELL_CONFIG" ] && ! echo "$PATH" | grep -q "$TARGET"; then
            echo "export PATH=\"\$PATH:$TARGET\"" >> "$SHELL_CONFIG"
            ok "Added $TARGET to PATH in $SHELL_CONFIG"
        fi
        ok "Installed to $TARGET/cortex"
    fi
done

if [ "$INSTALLED" = false ]; then
    error "Could not install to any location. Try: sudo ./scripts/install.sh"
fi

# ── Create plugins directory ────────────────────────────────
mkdir -p "${HOME}/.cortex/plugins"
mkdir -p "${HOME}/.cortex/memory"
ok "Created ~/.cortex/ directory structure"

# ── Verify ──────────────────────────────────────────────────
echo ""
if command -v cortex &>/dev/null; then
    ok "Cortex $(cortex --version 2>/dev/null || echo "v0.2.0") installed successfully!"
    echo ""
    info "Run 'cortex' to start"
    info "Run 'cortex --help' for options"
    echo ""
    info "Quick commands:"
    info "  /help       — Show help"
    info "  /tools      — List available tools"
    info "  /theme latte — Switch to light theme"
    info "  /plugin install <url> — Install a plugin from GitHub"
else
    warn "Cortex installed but not in PATH. Restart your terminal or run:"
    echo "  export PATH=\"\$PATH:${HOME}/.local/bin\""
    echo "  cortex"
fi
