#!/usr/bin/env bash
set -euo pipefail
APP=musacode
APP=musacode

MUTED='\033[0;2m'
RED='\033[0;31m'
ORANGE='\033[38;5;214m'
NC='\033[0m' # No Color

usage() {
    cat <<EOF
MUSACode Installer

Usage: install.sh [options]

Options:
    -h, --help              Display this help message
    -f, --force             Reinstall even if the target version is already installed
    -v, --version <version> Install a specific version (e.g., 1.0.180)
    -b, --binary <path>     Install from a local binary instead of downloading
        --no-modify-path    Don't modify shell config files (.zshrc, .bashrc, etc.)

Examples:
    curl -fsSL https://musacode.tos-cn-beijing.volces.com/install | bash
    curl -fsSL https://musacode.tos-cn-beijing.volces.com/install | bash -s -- --version 1.0.0.rc.1
    ./install --binary /path/to/musacode
EOF
}

requested_version=${VERSION:-}
force=false
no_modify_path=false
binary_path=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            usage
            exit 0
            ;;
        -f|--force)
            force=true
            shift
            ;;
        -v|--version)
            if [[ -n "${2:-}" ]]; then
                requested_version="$2"
                shift 2
            else
                echo -e "${RED}Error: --version requires a version argument${NC}"
                exit 1
            fi
            ;;
        -b|--binary)
            if [[ -n "${2:-}" ]]; then
                binary_path="$2"
                shift 2
            else
                echo -e "${RED}Error: --binary requires a path argument${NC}"
                exit 1
            fi
            ;;
        --no-modify-path)
            no_modify_path=true
            shift
            ;;
        *)
            echo -e "${ORANGE}Warning: Unknown option '$1'${NC}" >&2
            shift
            ;;
    esac
done

INSTALL_DIR=$HOME/.musacode/bin
mkdir -p "$INSTALL_DIR"

# If --binary is provided, skip all download/detection logic
if [ -n "$binary_path" ]; then
    if [ ! -f "$binary_path" ]; then
        echo -e "${RED}Error: Binary not found at ${binary_path}${NC}"
        exit 1
    fi
    specific_version="local"
else
    raw_os=$(uname -s)
    os=$(echo "$raw_os" | tr '[:upper:]' '[:lower:]')
    case "$raw_os" in
      Darwin*) os="darwin" ;;
      Linux*) os="linux" ;;
      MINGW*|MSYS*|CYGWIN*) os="windows" ;;
    esac

    arch=$(uname -m)
    if [[ "$arch" == "aarch64" ]]; then
      arch="arm64"
    fi
    if [[ "$arch" == "x86_64" ]]; then
      arch="x64"
    fi

    if [ "$os" = "darwin" ] && [ "$arch" = "x64" ]; then
      rosetta_flag=$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)
      if [ "$rosetta_flag" = "1" ]; then
        arch="arm64"
      fi
    fi

    combo="$os-$arch"
    case "$combo" in
      linux-x64|linux-arm64|darwin-x64|darwin-arm64|windows-x64)
        ;;
      *)
        echo -e "${RED}Unsupported OS/Arch: $os/$arch${NC}"
        exit 1
        ;;
    esac

    archive_ext=".zip"
    if [ "$os" = "linux" ]; then
      archive_ext=".tar.gz"
    fi

    is_musl=false
    if [ "$os" = "linux" ]; then
      if [ -f /etc/alpine-release ]; then
        is_musl=true
      fi

      if command -v ldd >/dev/null 2>&1; then
        if ldd --version 2>&1 | grep -qi musl; then
          is_musl=true
        fi
      fi
    fi

    needs_baseline=false
    if [ "$arch" = "x64" ]; then
      if [ "$os" = "linux" ]; then
        if ! grep -qwi avx2 /proc/cpuinfo 2>/dev/null; then
          needs_baseline=true
        fi
      fi

      if [ "$os" = "darwin" ]; then
        avx2=$(sysctl -n hw.optional.avx2_0 2>/dev/null || echo 0)
        if [ "$avx2" != "1" ]; then
          needs_baseline=true
        fi
      fi

      if [ "$os" = "windows" ]; then
        ps="(Add-Type -MemberDefinition \"[DllImport(\"\"kernel32.dll\"\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);\" -Name Kernel32 -Namespace Win32 -PassThru)::IsProcessorFeaturePresent(40)"
        out=""
        if command -v powershell.exe >/dev/null 2>&1; then
          out=$(powershell.exe -NoProfile -NonInteractive -Command "$ps" 2>/dev/null || true)
        elif command -v pwsh >/dev/null 2>&1; then
          out=$(pwsh -NoProfile -NonInteractive -Command "$ps" 2>/dev/null || true)
        fi
        out=$(echo "$out" | tr -d '\r' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
        if [ "$out" != "true" ] && [ "$out" != "1" ]; then
          needs_baseline=true
        fi
      fi
    fi

    target="$os-$arch"
    if [ "$needs_baseline" = "true" ]; then
      target="$target-baseline"
    fi
    if [ "$is_musl" = "true" ]; then
      target="$target-musl"
    fi

    filename="$APP-$target$archive_ext"


    if [ "$os" = "linux" ]; then
        if ! command -v tar >/dev/null 2>&1; then
             echo -e "${RED}Error: 'tar' is required but not installed.${NC}"
             exit 1
        fi
    else
        if ! command -v unzip >/dev/null 2>&1; then
            echo -e "${RED}Error: 'unzip' is required but not installed.${NC}"
            exit 1
        fi
    fi

    # TOS 下载基础 URL
    TOS_BASE_URL="https://musacode.tos-cn-beijing.volces.com"

    if [ -z "$requested_version" ]; then
        # Fetch latest version from TOS (always stored without v prefix)
        specific_version=$(curl -sfL "${TOS_BASE_URL}/latest" | tr -d '[:space:]')
        specific_version="${specific_version#v}"
        if [ -z "$specific_version" ]; then
            echo -e "${RED}Error: Failed to fetch latest version${NC}"
            exit 1
        fi
    else
        # Normalize: strip leading 'v' if present
        specific_version="${requested_version#v}"
    fi

    url="${TOS_BASE_URL}/v${specific_version}/$filename"

    if [ -n "$requested_version" ]; then
        # Verify the release exists before downloading
        http_status=$(curl -sI -o /dev/null -w "%{http_code}" "$url")
        if [ "$http_status" = "404" ]; then
            echo -e "${RED}Error: Release v${specific_version} not found${NC}"
            exit 1
        fi
    fi
fi

print_message() {
    local level=$1
    local message=$2
    local color=""

    case $level in
        info) color="${NC}" ;;
        warning) color="${NC}" ;;
        error) color="${RED}" ;;
    esac

    echo -e "${color}${message}${NC}"
}

check_version() {
    local version_file="$HOME/.musacode/.version"
    if [ -f "$version_file" ]; then
        local installed_version
        installed_version=$(cat "$version_file" 2>/dev/null || echo "")
        if [[ "$installed_version" == "$specific_version" ]]; then
            if [[ "$force" == "true" ]]; then
                print_message info "${MUTED}Version ${NC}$specific_version${MUTED} already installed, reinstalling${NC}"
                return
            fi
            print_message info "${MUTED}Version ${NC}$specific_version${MUTED} already installed${NC}"
            exit 0
        fi
        if [[ -n "$installed_version" ]]; then
            print_message info "${MUTED}Installed version: ${NC}$installed_version${MUTED}, updating to ${NC}$specific_version"
        fi
    fi
}

save_version() {
    mkdir -p "$HOME/.musacode"
    echo "$specific_version" > "$HOME/.musacode/.version"
}

print_progress() {
    local bytes="$1"
    local total="$2"
    local width=50
    local percent=$(( bytes * 100 / total ))
    [ "$percent" -gt 100 ] && percent=100
    local on=$(( percent * width / 100 ))
    local off=$(( width - on ))

    local filled=$(printf "%*s" "$on" "")
    filled=${filled// /■}
    local empty=$(printf "%*s" "$off" "")
    empty=${empty// /･}

    printf "\r${ORANGE}%s%s %3d%%${NC}" "$filled" "$empty" "$percent" > /dev/tty
}

download_with_progress() {
    local url="$1"
    local output="$2"

    # Get total file size via HEAD request
    local total_size
    total_size=$(curl -sI -L "$url" | grep -i content-length | tail -1 | awk '{print $2}' | tr -d '\r')

    if [ -z "$total_size" ] || ! [ "$total_size" -gt 0 ] 2>/dev/null; then
        curl -# -L -o "$output" "$url"
        return $?
    fi

    # Download silently in background
    curl -s -L -o "$output" "$url" &
    local curl_pid=$!

    # Hide cursor
    printf "\033[?25l" > /dev/tty

    # Monitor file size and show progress
    while kill -0 "$curl_pid" 2>/dev/null; do
        if [ -f "$output" ]; then
            local current
            current=$(wc -c < "$output" 2>/dev/null || echo 0)
            current=$(echo "$current" | tr -d ' ')
            print_progress "$current" "$total_size"
        fi
        sleep 0.1
    done

    wait "$curl_pid"
    local ret=$?

    # Show 100% on success
    if [ "$ret" -eq 0 ]; then
        print_progress "$total_size" "$total_size"
    fi

    # Show cursor, newline
    printf "\033[?25h\n" > /dev/tty

    return $ret
}

download_and_install() {
    print_message info "\n${MUTED}Installing ${NC}musacode ${MUTED}version: ${NC}$specific_version"
    local tmp_dir="${TMPDIR:-/tmp}/musacode_install_$$"
    mkdir -p "$tmp_dir"

    if [[ "$os" == "windows" ]] || ! [ -e /dev/tty ] || ! download_with_progress "$url" "$tmp_dir/$filename"; then
        # Fallback to standard curl on Windows, non-TTY environments, or if custom progress fails
        curl -# -L -o "$tmp_dir/$filename" "$url"
    fi

    if [ "$os" = "linux" ]; then
        tar -xzf "$tmp_dir/$filename" -C "$tmp_dir" 2>/dev/null
    else
        unzip -oq "$tmp_dir/$filename" -d "$tmp_dir" 2>/dev/null
    fi

    mv "$tmp_dir/musacode" "$INSTALL_DIR"
    chmod 755 "${INSTALL_DIR}/musacode"
    rm -rf "$tmp_dir"
}

install_from_binary() {
    print_message info "\n${MUTED}Installing ${NC}musacode ${MUTED}from: ${NC}$binary_path"
    cp "$binary_path" "${INSTALL_DIR}/musacode"
    chmod 755 "${INSTALL_DIR}/musacode"
}

if [ -n "$binary_path" ]; then
    install_from_binary
else
    check_version
    download_and_install
fi

save_version


add_to_path() {
    local config_file=$1
    local command=$2

    if grep -Fxq "$command" "$config_file"; then
        print_message info "Command already exists in $config_file, skipping write."
    elif [[ -w $config_file ]]; then
        echo -e "\n# musacode" >> "$config_file"
        echo "$command" >> "$config_file"
        print_message info "${MUTED}Successfully added ${NC}musacode ${MUTED}to \$PATH in ${NC}$config_file"
    else
        print_message warning "Manually add the directory to $config_file (or similar):"
        print_message info "  $command"
    fi
}

XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}

current_shell=$(basename "$SHELL")
case $current_shell in
    fish)
        config_files="$HOME/.config/fish/config.fish"
    ;;
    zsh)
        config_files="${ZDOTDIR:-$HOME}/.zshrc ${ZDOTDIR:-$HOME}/.zshenv $XDG_CONFIG_HOME/zsh/.zshrc $XDG_CONFIG_HOME/zsh/.zshenv"
    ;;
    bash)
        config_files="$HOME/.bashrc $HOME/.bash_profile $HOME/.profile $XDG_CONFIG_HOME/bash/.bashrc $XDG_CONFIG_HOME/bash/.bash_profile"
    ;;
    ash)
        config_files="$HOME/.ashrc $HOME/.profile /etc/profile"
    ;;
    sh)
        config_files="$HOME/.ashrc $HOME/.profile /etc/profile"
    ;;
    *)
        # Default case if none of the above matches
        config_files="$HOME/.bashrc $HOME/.bash_profile $XDG_CONFIG_HOME/bash/.bashrc $XDG_CONFIG_HOME/bash/.bash_profile"
    ;;
esac

if [[ "$no_modify_path" != "true" ]]; then
    config_file=""
    for file in $config_files; do
        if [[ -f $file ]]; then
            config_file=$file
            break
        fi
    done

    if [[ -z $config_file ]]; then
        print_message warning "No config file found for $current_shell. You may need to manually add to PATH:"
        print_message info "  export PATH=$INSTALL_DIR:\$PATH"
    elif [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
        case $current_shell in
            fish)
                add_to_path "$config_file" "fish_add_path $INSTALL_DIR"
            ;;
            zsh)
                add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
            ;;
            bash)
                add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
            ;;
            ash)
                add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
            ;;
            sh)
                add_to_path "$config_file" "export PATH=$INSTALL_DIR:\$PATH"
            ;;
            *)
                export PATH=$INSTALL_DIR:$PATH
                print_message warning "Manually add the directory to $config_file (or similar):"
                print_message info "  export PATH=$INSTALL_DIR:\$PATH"
            ;;
        esac
    fi
fi

if [ -n "${GITHUB_ACTIONS-}" ] && [ "${GITHUB_ACTIONS}" == "true" ]; then
    echo "$INSTALL_DIR" >> $GITHUB_PATH
    print_message info "Added $INSTALL_DIR to \$GITHUB_PATH"
fi

install_musacode_plugins() {
    curl -fsSL https://musacode.tos-cn-beijing.volces.com/desktop/install-plugins | bash 
}

install_musacode_plugins

echo -e ""
echo -e "${MUTED}                     ${NC}             ▄     "
echo -e "${MUTED}█▀▄▀█ █░░█ █▀▀▀ █▀▀█ ${NC}█▀▀▀ █▀▀█ █▀▀█ █▀▀█"
echo -e "${MUTED}█░▀░█ █░░█ ▀▀▀█ █▄▄█ ${NC}█░░░ █░░█ █░░█ █▀▀▀"
echo -e "${MUTED}▀░░░▀ ▀▀▀▀ ▀▀▀▀ ▀░░▀ ${NC}▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀"
echo -e ""
echo -e ""
echo -e "${MUTED}MUSACode includes free models, to start:${NC}"
echo -e ""
echo -e "cd <project>  ${MUTED}# Open directory${NC}"
echo -e "musacode      ${MUTED}# Run command${NC}"
echo -e ""
echo -e "${MUTED}For more information visit ${NC}https://code.mthreads.com/${NC}"
echo -e ""
echo -e ""
