#!/bin/bash
#
# Vigthoria CLI Installer
# Usage: curl -fsSL https://extension.vigthoria.io/downloads/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.45"
INSTALL_DIR="$HOME/.vigthoria"
MANIFEST_URL="https://extension.vigthoria.io/downloads/manifest.json"
HOSTED_TARBALL_URL="https://extension.vigthoria.io/downloads/vigthoria-cli-${CLI_VERSION}.tgz"
# The packaged installer resolves the signed manifest. The independently
# hosted installer is rendered after packing with this release's exact digest.
# The standalone installer uses this immutable digest when the packaged
# signature resolver is not locally available.
HOSTED_TARBALL_SHA256="9573f097dba52f79daac16894b2f2360b286bdefbff2adc73d6517c36a52df1c"
INSTALLER_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || true)"
RELEASE_RESOLVER="$INSTALLER_ROOT/scripts/release/resolve-release-manifest.mjs"
RELEASE_INSTALLER="$INSTALLER_ROOT/scripts/release/install-release.mjs"

validate_release_url() {
    node - "$1" <<'NODE'
const value = process.argv[2];
try {
    const parsed = new URL(value);
    const valid = parsed.protocol === 'https:' && parsed.hostname === 'extension.vigthoria.io'
        && parsed.port === '' && !parsed.username && !parsed.password
        && !/[\\\x00-\x20\x7f]/.test(value);
    process.exitCode = valid ? 0 : 1;
} catch { process.exitCode = 1; }
NODE
}

resolve_release_manifest() {
    # Direct artifacts are accepted only when the packaged shared verifier is
    # present and validates the strict manifest plus detached Ed25519 signature.
    # A curl-piped installer therefore stays pinned to the immutable extension
    # archive instead of changing package origins.
    if [[ ! -f "$RELEASE_RESOLVER" ]] || ! command -v node >/dev/null 2>&1; then
        return 0
    fi

    if ! validate_release_url "$MANIFEST_URL"; then
        echo "Refusing untrusted release manifest URL" >&2
        exit 1
    fi
    local resolved_json
    resolved_json="$(node "$RELEASE_RESOLVER" "$MANIFEST_URL" stable 2>/dev/null || true)"
    if [[ -z "$resolved_json" ]]; then
        return 0
    fi

    local resolved
    resolved="$(printf '%s' "$resolved_json" | node -e '
try {
    const data = JSON.parse(require("node:fs").readFileSync(0, "utf8"));
    const fields = [data.version, data.url, data.sha256];
    if (fields.every(value => typeof value === "string" && value.trim() && !/[\r\n]/.test(value))) {
        process.stdout.write(fields.map(value => value.trim()).join("\n") + "\n");
    }
} catch { process.exitCode = 1; }
' 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
            if ! validate_release_url "$manifest_url"; then
                echo "Refusing untrusted release artifact URL" >&2
                exit 1
            fi
            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 "No signed Vigthoria CLI release is available for this operating system."
            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
prepare_temp_root() {
    local requested_root="${VIGTHORIA_TEMP_DIR:-$HOME/.vigthoria/tmp}"
    case "$requested_root" in
        /*) ;;
        *) echo -e "${RED}VIGTHORIA_TEMP_DIR must be an absolute local path${NC}" >&2; return 1 ;;
    esac
    if [[ "$requested_root" == "/" || "$requested_root" == "${TMPDIR:-/tmp}" ]]; then
        echo -e "${RED}Refusing shared or filesystem-root temporary storage${NC}" >&2
        return 1
    fi
    mkdir -p "$requested_root"
    local path_cursor="$requested_root"
    while [[ "$path_cursor" != "/" ]]; do
        if [[ -L "$path_cursor" ]]; then
            echo -e "${RED}Refusing a symbolic-link temporary storage path${NC}" >&2
            return 1
        fi
        path_cursor="$(dirname -- "$path_cursor")"
    done
    local resolved_root resolved_home
    resolved_root="$(cd "$requested_root" && pwd -P)"
    resolved_home="$(cd "$HOME" && pwd -P)"
    case "$resolved_root" in
        /tmp|/var/tmp|/usr/tmp) echo -e "${RED}Refusing shared temporary storage${NC}" >&2; return 1 ;;
    esac
    if [[ -z "${VIGTHORIA_TEMP_DIR:-}" ]]; then
        case "$resolved_root/" in
            "$resolved_home/"*) ;;
            *) echo -e "${RED}Default temporary storage escaped the user home${NC}" >&2; return 1 ;;
        esac
    fi
    chmod 700 "$resolved_root"
    printf '%s\n' "$resolved_root"
}

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..."
        VIGTHORIA_INSTALL_TEMP_ROOT="$(prepare_temp_root)" || return 1
        RELEASE_TMP_DIR="$(mktemp -d "$VIGTHORIA_INSTALL_TEMP_ROOT/install.XXXXXX")"
        RELEASE_ARCHIVE="$RELEASE_TMP_DIR/vigthoria-cli-${CLI_VERSION}.tgz"
        if ! validate_release_url "$HOSTED_TARBALL_URL"; then
            echo -e "${RED}Refusing untrusted release artifact URL${NC}"
            return 1
        fi
        if ! curl -fsS --proto '=https' --max-redirs 0 "$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
        if [[ ! -f "$RELEASE_INSTALLER" ]]; then
            RELEASE_BOOTSTRAP="$RELEASE_TMP_DIR/bootstrap"
            mkdir "$RELEASE_BOOTSTRAP"
            tar -xzf "$RELEASE_ARCHIVE" -C "$RELEASE_BOOTSTRAP"
            RELEASE_INSTALLER="$RELEASE_BOOTSTRAP/package/scripts/release/install-release.mjs"
            if [[ ! -f "$RELEASE_INSTALLER" ]]; then
                echo -e "${RED}✗ Verified release is missing its transactional installer${NC}"
                return 1
            fi
        fi
        node "$RELEASE_INSTALLER" "$RELEASE_ARCHIVE" "$CLI_VERSION"
        rm -rf "$RELEASE_TMP_DIR"
    else
        echo -e "${RED}✗ No checksum-verified extension release ${CLI_VERSION} is available${NC}"
        return 1
    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}"
    COMPLETION_ROOT="$INSTALLER_ROOT/completions"
    if [[ ! -d "$COMPLETION_ROOT" ]] && [[ -d "$HOME/.vigthoria/cli/current/node_modules/vigthoria-cli/completions" ]]; then
        COMPLETION_ROOT="$HOME/.vigthoria/cli/current/node_modules/vigthoria-cli/completions"
    fi
    if [[ ! -d "$COMPLETION_ROOT" ]]; then
        echo -e "${YELLOW}⚠ Generated completions are unavailable; no stale static list was installed.${NC}"
        return 0
    fi
    SHELL_NAME=$(basename "$SHELL")
    case "$SHELL_NAME" in
        bash)
            COMPLETION_FILE="$HOME/.bash_completion.d/vigthoria"
            mkdir -p "$HOME/.bash_completion.d"
            install -m 0644 "$COMPLETION_ROOT/vigthoria.bash" "$COMPLETION_FILE"
            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"
            install -m 0644 "$COMPLETION_ROOT/_vigthoria" "$COMPLETION_FILE"
            echo -e "${GREEN}✓ Zsh completion installed${NC}"
            echo "  Add to ~/.zshrc: fpath=(~/.zsh/completion \$fpath)"
            ;;
        fish)
            COMPLETION_FILE="$HOME/.config/fish/completions/vigthoria.fish"
            mkdir -p "$HOME/.config/fish/completions"
            install -m 0644 "$COMPLETION_ROOT/vigthoria.fish" "$COMPLETION_FILE"
            echo -e "${GREEN}✓ Fish completion installed${NC}"
            ;;
        *)
            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 "$@"
