#!/bin/bash
set -e

# Makima CLI Installer
# Usage: curl -fsSL https://raw.githubusercontent.com/soryu-co/soryu/master/install.sh | bash
#        curl -fsSL https://raw.githubusercontent.com/soryu-co/soryu/master/install.sh | INSTALL_DIR=/opt/bin bash

REPO="soryu-co/soryu"
INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"
BINARY_NAME="makima"

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

print_error() {
    echo -e "${RED}Error: $1${NC}" >&2
}

print_success() {
    echo -e "${GREEN}$1${NC}"
}

print_warning() {
    echo -e "${YELLOW}$1${NC}"
}

print_info() {
    echo "$1"
}

# Check for required tools
check_dependencies() {
    local missing=""

    if ! command -v curl &> /dev/null; then
        missing="$missing curl"
    fi

    if ! command -v tar &> /dev/null; then
        missing="$missing tar"
    fi

    if [ -n "$missing" ]; then
        print_error "Missing required tools:$missing"
        print_info "Please install the missing tools and try again."
        exit 1
    fi
}

# Detect operating system
detect_os() {
    local os
    os="$(uname -s)"

    case "$os" in
        Linux*)
            echo "linux"
            ;;
        Darwin*)
            echo "macos"
            ;;
        *)
            print_error "Unsupported operating system: $os"
            print_info "Supported: Linux, macOS"
            exit 1
            ;;
    esac
}

# Detect CPU architecture
detect_arch() {
    local arch
    arch="$(uname -m)"

    case "$arch" in
        x86_64|amd64)
            echo "x86_64"
            ;;
        arm64|aarch64)
            echo "arm64"
            ;;
        *)
            print_error "Unsupported architecture: $arch"
            print_info "Supported: x86_64, arm64"
            exit 1
            ;;
    esac
}

# Get the latest release version from GitHub API
get_latest_version() {
    local version
    version=$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')

    if [ -z "$version" ]; then
        print_error "Failed to fetch latest release version from GitHub"
        exit 1
    fi

    echo "$version"
}

# Construct the download URL for the release asset
get_download_url() {
    local version=$1
    local os=$2
    local arch=$3

    # Handle macOS arm64 vs Linux x86_64 naming
    local asset_name="makima-${version}-${os}-${arch}.tar.gz"

    echo "https://github.com/$REPO/releases/download/${version}/${asset_name}"
}

# Download and install the binary
install_binary() {
    local url=$1
    local tmpdir
    tmpdir=$(mktemp -d)
    local tarball="$tmpdir/makima.tar.gz"

    print_info "Downloading from: $url"

    # Download the tarball
    if ! curl -fsSL "$url" -o "$tarball"; then
        print_error "Failed to download release from: $url"
        print_info "Please check if the release exists for your platform."
        rm -rf "$tmpdir"
        exit 1
    fi

    # Verify download was successful
    if [ ! -f "$tarball" ] || [ ! -s "$tarball" ]; then
        print_error "Downloaded file is empty or missing"
        rm -rf "$tmpdir"
        exit 1
    fi

    # Extract the tarball
    print_info "Extracting archive..."
    if ! tar -xzf "$tarball" -C "$tmpdir"; then
        print_error "Failed to extract archive"
        rm -rf "$tmpdir"
        exit 1
    fi

    # Find the binary (it should be in the extracted files)
    local binary
    if [ -f "$tmpdir/$BINARY_NAME" ]; then
        binary="$tmpdir/$BINARY_NAME"
    elif [ -f "$tmpdir/makima/$BINARY_NAME" ]; then
        binary="$tmpdir/makima/$BINARY_NAME"
    else
        # Search for the binary
        binary=$(find "$tmpdir" -name "$BINARY_NAME" -type f | head -1)
        if [ -z "$binary" ]; then
            print_error "Could not find $BINARY_NAME binary in archive"
            print_info "Archive contents:"
            ls -la "$tmpdir"
            rm -rf "$tmpdir"
            exit 1
        fi
    fi

    # Make binary executable
    chmod +x "$binary"

    # Create install directory if it doesn't exist
    if [ ! -d "$INSTALL_DIR" ]; then
        print_info "Creating directory: $INSTALL_DIR"
        if ! mkdir -p "$INSTALL_DIR" 2>/dev/null; then
            print_warning "Cannot create $INSTALL_DIR, trying with sudo..."
            sudo mkdir -p "$INSTALL_DIR"
        fi
    fi

    # Install binary
    print_info "Installing to: $INSTALL_DIR/$BINARY_NAME"
    if ! mv "$binary" "$INSTALL_DIR/$BINARY_NAME" 2>/dev/null; then
        print_warning "Cannot write to $INSTALL_DIR, trying with sudo..."
        sudo mv "$binary" "$INSTALL_DIR/$BINARY_NAME"
    fi

    # Cleanup
    rm -rf "$tmpdir"
}

# Verify installation
verify_installation() {
    if [ -x "$INSTALL_DIR/$BINARY_NAME" ]; then
        print_success "Successfully installed $BINARY_NAME to $INSTALL_DIR/$BINARY_NAME"

        # Check if install dir is in PATH
        if ! echo "$PATH" | grep -q "$INSTALL_DIR"; then
            print_warning "Note: $INSTALL_DIR is not in your PATH"
            print_info "Add it with: export PATH=\"$INSTALL_DIR:\$PATH\""
        fi

        # Show version if possible
        if command -v "$BINARY_NAME" &> /dev/null; then
            print_info ""
            print_info "Installed version:"
            "$BINARY_NAME" --version 2>/dev/null || true
        fi
    else
        print_error "Installation failed - binary not found at $INSTALL_DIR/$BINARY_NAME"
        exit 1
    fi
}

# Main installation flow
main() {
    print_info "Makima CLI Installer"
    print_info "===================="
    print_info ""

    # Check dependencies
    check_dependencies

    # Detect platform
    local os arch
    os=$(detect_os)
    arch=$(detect_arch)
    print_info "Detected platform: $os-$arch"

    # Get latest version
    print_info "Fetching latest release..."
    local version
    version=$(get_latest_version)
    print_info "Latest version: $version"

    # Construct download URL
    local url
    url=$(get_download_url "$version" "$os" "$arch")

    # Download and install
    print_info ""
    install_binary "$url"

    # Verify
    print_info ""
    verify_installation

    print_info ""
    print_success "Installation complete!"
}

main "$@"
