#!/usr/bin/env bash
# AyaanScript+ — Linux / macOS installer
# Installs `ayaan` and `aspkg` from crates.io.
# Bootstraps Rust via rustup if cargo isn't already on PATH.
#
# Usage:
#   curl -sSf https://raw.githubusercontent.com/ayaan511/AyaanScriptPlus/master/installer/install.sh | bash
#   OR
#   bash install.sh

set -e

VERSION="1.36.0"
BOLD=$(tput bold 2>/dev/null || true)
RESET=$(tput sgr0 2>/dev/null || true)
CYAN=$(tput setaf 6 2>/dev/null || true)
GREEN=$(tput setaf 2 2>/dev/null || true)
YELLOW=$(tput setaf 3 2>/dev/null || true)
RED=$(tput setaf 1 2>/dev/null || true)

banner() {
    echo ""
    echo "${CYAN}+==================================================+${RESET}"
    echo "${CYAN}|${RESET}         ${BOLD}A Y A A N S C R I P T   +${RESET}                ${CYAN}|${RESET}"
    echo "${CYAN}|${RESET}             Installer (Linux/macOS)              ${CYAN}|${RESET}"
    echo "${CYAN}|${RESET}                  v${VERSION}                              ${CYAN}|${RESET}"
    echo "${CYAN}+==================================================+${RESET}"
    echo ""
}

detect_os() {
    case "$(uname -s)" in
        Linux*)  OS=linux ;;
        Darwin*) OS=macos ;;
        *)       OS=unknown ;;
    esac
    echo "[i] Detected OS: ${OS}"
    if [ "$OS" = "unknown" ]; then
        echo "${RED}[!]${RESET} Unsupported OS. This installer is for Linux and macOS."
        echo "    For Windows, use AyaanScriptPlus-Setup.exe."
        exit 1
    fi
}

ensure_cargo() {
    echo "${BOLD}[1/3]${RESET} Checking for Rust toolchain..."
    if command -v cargo >/dev/null 2>&1; then
        echo "      Found: $(cargo --version)"
        return 0
    fi

    echo "      Rust not found — bootstrapping rustup..."
    if ! command -v curl >/dev/null 2>&1; then
        echo "${RED}[!]${RESET} curl is required to install Rust. Install curl and re-run."
        exit 1
    fi

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal

    # Make cargo available in this shell session
    if [ -f "$HOME/.cargo/env" ]; then
        # shellcheck disable=SC1091
        . "$HOME/.cargo/env"
    fi
    export PATH="$HOME/.cargo/bin:$PATH"

    if ! command -v cargo >/dev/null 2>&1; then
        echo "${RED}[!]${RESET} cargo still not on PATH after rustup install."
        echo "    Open a new shell and re-run: bash install.sh"
        exit 1
    fi
    echo "${GREEN}      Rust installed.${RESET}"
}

install_ayaan() {
    echo ""
    echo "${BOLD}[2/3]${RESET} Installing AyaanScript+ from crates.io..."
    echo "      Running: cargo install ayaan --force"

    if ! cargo install ayaan --force; then
        echo "${RED}[!]${RESET} cargo install ayaan failed."
        echo "    If the failure mentions OpenSSL or pkg-config, install the dev"
        echo "    packages for your distro:"
        echo "      Debian/Ubuntu:  sudo apt install pkg-config libssl-dev"
        echo "      Fedora/RHEL:    sudo dnf install pkgconfig openssl-devel"
        echo "      Arch:           sudo pacman -S pkg-config openssl"
        echo "      macOS:          (usually already present via Xcode CLT)"
        exit 1
    fi
    echo "${GREEN}      Installed.${RESET}"
}

verify_and_path() {
    echo ""
    echo "${BOLD}[3/3]${RESET} Verifying install..."
    local bin="$HOME/.cargo/bin"
    if [ -x "$bin/ayaan" ] && [ -x "$bin/aspkg" ]; then
        echo "      Found: $bin/ayaan"
        echo "      Found: $bin/aspkg"
    else
        echo "${YELLOW}      WARNING:${RESET} expected binaries not found in $bin"
    fi

    # Persist PATH update so a fresh shell picks up cargo bin
    local shell_rc=""
    case "$SHELL" in
        */zsh)  shell_rc="$HOME/.zshrc" ;;
        */bash) shell_rc="$HOME/.bashrc" ;;
        *)      shell_rc="" ;;
    esac

    if [ -n "$shell_rc" ] && [ -f "$shell_rc" ]; then
        if ! grep -q '.cargo/bin' "$shell_rc" 2>/dev/null; then
            echo "      Adding \$HOME/.cargo/bin to $shell_rc"
            {
                echo ""
                echo "# Added by AyaanScript+ installer"
                echo 'export PATH="$HOME/.cargo/bin:$PATH"'
            } >> "$shell_rc"
        fi
    fi
}

show_done() {
    echo ""
    echo "${GREEN}+==================================================+${RESET}"
    echo "${GREEN}|${RESET}             Installation complete!              ${GREEN}|${RESET}"
    echo "${GREEN}+==================================================+${RESET}"
    echo ""
    echo "Open a ${BOLD}new${RESET} terminal (or run \`source ~/.${SHELL##*/}rc\`) and try:"
    echo "    ${CYAN}ayaan${RESET}                       (starts the REPL)"
    echo "    ${CYAN}ayaan myfile.ayaan${RESET}          (runs a script)"
    echo "    ${CYAN}aspkg help${RESET}                  (package manager)"
    echo ""
    echo "Demos to try (clone or download the source repo for these):"
    echo "    ayaan demos/bounce.ayaan"
    echo "    ayaan demos/starfield.ayaan"
    echo "    ayaan demos/clock.ayaan"
    echo "    ayaan demos/plasma.ayaan"
    echo ""
}

main() {
    banner
    detect_os
    ensure_cargo
    install_ayaan
    verify_and_path
    show_done
}

main "$@"
