#!/bin/bash
#
# Vigthoria CLI Installer
# Usage: curl -fsSL https://cli.vigthoria.io/install.sh | bash
#
# Supports: Linux, macOS (Intel and Apple Silicon)
#

set -e

# Colors (with fallback for non-color terminals)
if [ -t 1 ] && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    CYAN='\033[0;36m'
    WHITE='\033[1;37m'
    NC='\033[0m' # No Color
else
    RED=''
    GREEN=''
    YELLOW=''
    CYAN=''
    WHITE=''
    NC=''
fi

# Configuration
CLI_VERSION="1.13.13"
INSTALL_DIR="$HOME/.vigthoria"
REPO_URL="https://market.vigthoria.io/vigthoria/vigthoria-cli"
GIT_PACKAGE_URL="git+https://market.vigthoria.io/vigthoria/vigthoria-cli.git"
MANIFEST_URL="${VIGTHORIA_UPDATE_MANIFEST_URL:-https://extension.vigthoria.io/downloads/manifest.json}"
HOSTED_TARBALL_URL="https://extension.vigthoria.io/downloads/vigthoria-cli-${CLI_VERSION}.tgz"
HOSTED_TARBALL_SHA256=""

resolve_release_manifest() {
    if ! command -v curl >/dev/null 2>&1 || ! command -v python3 >/dev/null 2>&1; then
        return 0
    fi

    local manifest_json
    manifest_json="$(curl -fsSL "$MANIFEST_URL" 2>/dev/null || true)"
    if [[ -z "$manifest_json" ]]; then
        return 0
    fi

    local resolved
    resolved="$(printf '%s' "$manifest_json" | python3 -c "
import json, sys
try:
    data = json.load(sys.stdin)
    stable = (data.get('channels') or {}).get('stable') or {}
    version = str(stable.get('version') or '').strip()
    url = str(stable.get('url') or '').strip()
    sha256 = str(stable.get('sha256') or '').strip().lower()
    if version:
        print(version)
    if url:
        print(url)
    if sha256:
        print(sha256)
except Exception:
    pass
" 2>/dev/null || true)"

    if [[ -n "$resolved" ]]; then
        # macOS ships Bash 3.2, which does not provide mapfile/readarray.
        # Parse the two-line response with POSIX sed instead.
        manifest_version="$(printf '%s\n' "$resolved" | sed -n '1p')"
        manifest_url="$(printf '%s\n' "$resolved" | sed -n '2p')"
        manifest_sha256="$(printf '%s\n' "$resolved" | sed -n '3p')"
        if [[ -n "$manifest_version" ]]; then
            CLI_VERSION="$manifest_version"
        fi
        if [[ -n "$manifest_url" ]]; then
            HOSTED_TARBALL_URL="$manifest_url"
        elif [[ -n "$manifest_version" ]]; then
            HOSTED_TARBALL_URL="https://extension.vigthoria.io/downloads/vigthoria-cli-${CLI_VERSION}.tgz"
        fi
        if [[ "$manifest_sha256" =~ ^[a-f0-9]{64}$ ]]; then
            HOSTED_TARBALL_SHA256="$manifest_sha256"
        fi
    fi
}

resolve_release_manifest

# Detect platform and set appropriate bin directory
detect_platform() {
    OS="$(uname -s)"
    ARCH="$(uname -m)"
    
    case "$OS" in
        Darwin)
            PLATFORM="macos"
            # macOS: Check if /usr/local/bin is writable, otherwise use ~/.local/bin
            if [ -w "/usr/local/bin" ]; then
                BIN_DIR="/usr/local/bin"
            else
                BIN_DIR="$HOME/.local/bin"
                mkdir -p "$BIN_DIR"
            fi
            ;;
        Linux)
            PLATFORM="linux"
            # Linux: Prefer ~/.local/bin for user installs
            if [ -w "/usr/local/bin" ]; then
                BIN_DIR="/usr/local/bin"
            else
                BIN_DIR="$HOME/.local/bin"
                mkdir -p "$BIN_DIR"
            fi
            ;;
        *)
            echo -e "${RED}Unsupported operating system: $OS${NC}"
            echo "Please use the npm install method: npm install -g vigthoria-cli"
            exit 1
            ;;
    esac
    
    echo -e "${CYAN}Detected: $PLATFORM ($ARCH)${NC}"
}

echo -e "${CYAN}"
echo "╔═══════════════════════════════════════════════════════════╗"
echo "║                                                           ║"
echo "║         VIGTHORIA CLI INSTALLER v${CLI_VERSION}                  ║"
echo "║         AI-Powered Terminal Coding Assistant              ║"
echo "║                                                           ║"
echo "╚═══════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Check requirements
check_requirements() {
    echo -e "${CYAN}Checking requirements...${NC}"
    
    detect_platform
    
    # Check Node.js
    if ! command -v node &> /dev/null; then
        echo -e "${RED}✗ Node.js is not installed${NC}"
        echo ""
        echo "  Please install Node.js 20.19 or later:"
        if [ "$PLATFORM" = "macos" ]; then
            echo "    brew install node"
            echo "    or download from: https://nodejs.org/"
        else
            echo "    # Ubuntu/Debian:"
            echo "    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -"
            echo "    sudo apt-get install -y nodejs"
            echo ""
            echo "    # Or download from: https://nodejs.org/"
        fi
        exit 1
    fi
    
    NODE_VERSION_FULL=$(node -v | sed 's/^v//')
    NODE_VERSION_MAJOR=$(printf '%s' "$NODE_VERSION_FULL" | cut -d'.' -f1)
    NODE_VERSION_MINOR=$(printf '%s' "$NODE_VERSION_FULL" | cut -d'.' -f2)
    if [ "$NODE_VERSION_MAJOR" -lt 20 ] || { [ "$NODE_VERSION_MAJOR" -eq 20 ] && [ "$NODE_VERSION_MINOR" -lt 19 ]; }; then
        echo -e "${RED}✗ Node.js version must be 20.19 or higher (found: v$NODE_VERSION_FULL)${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Node.js v$(node -v | cut -d'v' -f2)${NC}"
    
    # Check npm
    if ! command -v npm &> /dev/null; then
        echo -e "${RED}✗ npm is not installed${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ npm v$(npm -v)${NC}"
    
    # Check git (optional)
    if command -v git &> /dev/null; then
        echo -e "${GREEN}✓ git v$(git --version | cut -d' ' -f3)${NC}"
    else
        echo -e "${YELLOW}⚠ git not found (optional, for project context)${NC}"
    fi
    
    echo ""
}

# Install CLI
install_cli() {
    echo -e "${CYAN}Installing Vigthoria CLI...${NC}"
    
    # Create install directory
    mkdir -p "$INSTALL_DIR"
    
    # Option 1: Download and verify the exact hosted release package.
    if [[ -n "$HOSTED_TARBALL_SHA256" ]]; then
        echo "Downloading checksum-verified hosted release package..."
        RELEASE_TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/vigthoria-cli-install.XXXXXX")"
        RELEASE_ARCHIVE="$RELEASE_TMP_DIR/vigthoria-cli-${CLI_VERSION}.tgz"
        if ! curl -fsSL "$HOSTED_TARBALL_URL" -o "$RELEASE_ARCHIVE"; then
            rm -rf "$RELEASE_TMP_DIR"
            echo -e "${RED}✗ Failed to download verified release package${NC}"
            exit 1
        fi
        if command -v shasum >/dev/null 2>&1; then
            ACTUAL_SHA256="$(shasum -a 256 "$RELEASE_ARCHIVE" | awk '{print $1}')"
        elif command -v sha256sum >/dev/null 2>&1; then
            ACTUAL_SHA256="$(sha256sum "$RELEASE_ARCHIVE" | awk '{print $1}')"
        else
            rm -rf "$RELEASE_TMP_DIR"
            echo -e "${RED}✗ SHA-256 verification tool is unavailable${NC}"
            exit 1
        fi
        if [[ "$ACTUAL_SHA256" != "$HOSTED_TARBALL_SHA256" ]]; then
            rm -rf "$RELEASE_TMP_DIR"
            echo -e "${RED}✗ Release checksum verification failed${NC}"
            exit 1
        fi
        npm install -g --force "$RELEASE_ARCHIVE"
        rm -rf "$RELEASE_TMP_DIR"
    elif npm view vigthoria-cli version &> /dev/null; then
        echo "Installing from npm registry..."
        npm install -g --force vigthoria-cli
    elif npm install -g --force "$GIT_PACKAGE_URL"; then
        echo "Installed from git package fallback."
    else
        # Option 2: Install from local or git
        echo "Installing from source..."
        
        # Check if we're in the CLI directory
        if [ -f "package.json" ] && grep -q '"name": "vigthoria-cli"' package.json; then
            echo "Installing from current directory..."
            npm install
            npm run build
            npm link
        else
            # Clone from repo
            echo "Cloning from repository..."
            git clone "$REPO_URL" "$INSTALL_DIR/cli" 2>/dev/null || {
                echo -e "${YELLOW}Repository not available, using local install${NC}"
                # Copy local files for development
                SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
                if [ -d "$SCRIPT_DIR/../src" ]; then
                    cp -r "$SCRIPT_DIR/.." "$INSTALL_DIR/cli"
                fi
            }
            
            if [ -d "$INSTALL_DIR/cli" ]; then
                cd "$INSTALL_DIR/cli"
                npm install
                npm run build
                npm link
            fi
        fi
    fi
    
    echo -e "${GREEN}✓ Installation complete${NC}"
    echo ""
}

# Create symlinks
create_symlinks() {
    echo -e "${CYAN}Creating command shortcuts...${NC}"
    
    # Check if vigthoria command exists
    if command -v vigthoria &> /dev/null; then
        echo -e "${GREEN}✓ 'vigthoria' command available${NC}"
    fi
    
    # Create 'vig' alias if not exists
    if ! command -v vig &> /dev/null; then
        if [ -w "$BIN_DIR" ]; then
            ln -sf "$(which vigthoria)" "$BIN_DIR/vig" 2>/dev/null || true
        fi
    fi
    
    if command -v vig &> /dev/null; then
        echo -e "${GREEN}✓ 'vig' shortcut available${NC}"
    fi
    
    echo ""
}

# Setup shell completion
setup_completion() {
    echo -e "${CYAN}Setting up shell completion...${NC}"
    
    # Detect shell
    SHELL_NAME=$(basename "$SHELL")
    
    case "$SHELL_NAME" in
        bash)
            COMPLETION_FILE="$HOME/.bash_completion.d/vigthoria"
            mkdir -p "$HOME/.bash_completion.d"
            cat > "$COMPLETION_FILE" << 'EOF'
_vigthoria_completions() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local commands="chat edit generate explain fix review login logout status config init"
    COMPREPLY=($(compgen -W "$commands" -- "$cur"))
}
complete -F _vigthoria_completions vigthoria
complete -F _vigthoria_completions vig
EOF
            echo -e "${GREEN}✓ Bash completion installed${NC}"
            echo "  Run: source ~/.bash_completion.d/vigthoria"
            ;;
        zsh)
            COMPLETION_FILE="$HOME/.zsh/completion/_vigthoria"
            mkdir -p "$HOME/.zsh/completion"
            cat > "$COMPLETION_FILE" << 'EOF'
#compdef vigthoria vig

_vigthoria() {
    local -a commands
    commands=(
        'chat:Start interactive chat with AI'
        'edit:Edit a file with AI assistance'
        'generate:Generate code from description'
        'explain:Explain code in a file'
        'fix:Fix issues in a file'
        'review:Review code quality'
        'login:Login to Vigthoria'
        'logout:Logout from Vigthoria'
        'status:Show account status'
        'config:Configure settings'
        'init:Initialize project'
    )
    _describe 'command' commands
}

_vigthoria "$@"
EOF
            echo -e "${GREEN}✓ Zsh completion installed${NC}"
            echo "  Add to ~/.zshrc: fpath=(~/.zsh/completion \$fpath)"
            ;;
        *)
            echo -e "${YELLOW}⚠ Shell completion not available for $SHELL_NAME${NC}"
            ;;
    esac
    
    echo ""
}

# Print success message
print_success() {
    echo -e "${GREEN}"
    echo "╔═══════════════════════════════════════════════════════════╗"
    echo "║                                                           ║"
    echo "║         ✓ VIGTHORIA CLI INSTALLED SUCCESSFULLY!           ║"
    echo "║                                                           ║"
    echo "╚═══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    echo -e "${CYAN}Quick Start:${NC}"
    echo ""
    echo "  1. Login to your account:"
    echo -e "     ${WHITE}vigthoria login${NC}"
    echo ""
    echo "  2. Start coding with AI:"
    echo -e "     ${WHITE}vigthoria chat${NC}"
    echo ""
    echo "  3. Edit a file:"
    echo -e "     ${WHITE}vigthoria edit myfile.ts${NC}"
    echo ""
    echo "  4. Generate code:"
    echo -e "     ${WHITE}vigthoria generate \"REST API endpoint\"${NC}"
    echo ""
    echo -e "${CYAN}Commands:${NC}"
    echo "  vigthoria chat      - Interactive AI chat"
    echo "  vigthoria edit      - Edit files with AI"
    echo "  vigthoria generate  - Generate code"
    echo "  vigthoria explain   - Explain code"
    echo "  vigthoria fix       - Fix code issues"
    echo "  vigthoria review    - Code review"
    echo "  vigthoria --help    - Show all commands"
    echo ""
    echo -e "${CYAN}Shortcuts:${NC}"
    echo "  vig c  = vigthoria chat"
    echo "  vig e  = vigthoria edit"
    echo "  vig g  = vigthoria generate"
    echo ""
    echo -e "Documentation: ${CYAN}https://docs.vigthoria.io/cli${NC}"
    echo ""
}

# Main installation flow
main() {
    check_requirements
    install_cli
    create_symlinks
    setup_completion
    print_success
}

# Run main
main "$@"
