#!/bin/bash
set -euo pipefail

# TypeDialog Installation Script
# Installs TypeDialog binaries and configuration

INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/bin}"
CONFIG_DIR="${CONFIG_DIR:-$HOME/.config/typedialog}"
GITHUB_REPO="anthropics/typedialog"
VERSION="${VERSION:-latest}"

# Function: Print info message
log_info() {
    echo "[INFO] $*" >&2
}

# Function: Print error message
log_error() {
    echo "[ERROR] $*" >&2
}

# Function: Print success message
log_success() {
    echo "[✓] $*" >&2
}

# Function: Detect OS and architecture
detect_platform() {
    local os
    local arch

    os=$(uname -s)
    arch=$(uname -m)

    case "$os" in
        Linux*)
            os="linux"
            ;;
        Darwin*)
            os="darwin"
            ;;
        *)
            log_error "Unsupported OS: $os"
            return 1
            ;;
    esac

    case "$arch" in
        x86_64)
            arch="x86_64"
            ;;
        aarch64)
            arch="aarch64"
            ;;
        arm64)
            arch="aarch64"
            ;;
        *)
            log_error "Unsupported architecture: $arch"
            return 1
            ;;
    esac

    echo "${os}-${arch}"
}

# Function: Create directories
create_dirs() {
    mkdir -p "$INSTALL_DIR" || {
        log_error "Failed to create install directory: $INSTALL_DIR"
        return 1
    }

    mkdir -p "$CONFIG_DIR" || {
        log_error "Failed to create config directory: $CONFIG_DIR"
        return 1
    }

    log_success "Directories created"
}

# Function: Download release
download_release() {
    local platform="$1"
    local download_url="https://github.com/${GITHUB_REPO}/releases/download/${VERSION}/typedialog-${platform}.tar.gz"
    local temp_file
    temp_file=$(mktemp) || return 1
    trap 'rm -f '"$temp_file" EXIT

    log_info "Downloading: $download_url"

    if command -v curl &>/dev/null; then
        curl -fsSL "$download_url" -o "$temp_file" || {
            log_error "Download failed"
            return 1
        }
    elif command -v wget &>/dev/null; then
        wget -q "$download_url" -O "$temp_file" || {
            log_error "Download failed"
            return 1
        }
    else
        log_error "curl or wget required"
        return 1
    fi

    log_success "Download complete"
    echo "$temp_file"
}

# Function: Extract archive
extract_archive() {
    local archive="$1"
    local extract_dir
    extract_dir=$(mktemp -d) || return 1

    log_info "Extracting archive..."
    tar -xzf "$archive" -C "$extract_dir" || {
        log_error "Extraction failed"
        rm -rf "$extract_dir"
        return 1
    }

    echo "$extract_dir"
}

# Function: Install binaries
install_binaries() {
    local extract_dir="$1"

    for binary in typedialog typedialog-tui typedialog-web typedialog-ai typedialog-ag typedialog-prov-gen; do
        local binary_path="${extract_dir}/bin/${binary}"

        if [[ -f "$binary_path" ]]; then
            cp "$binary_path" "${INSTALL_DIR}/${binary}" || {
                log_error "Failed to install: $binary"
                return 1
            }
            chmod +x "${INSTALL_DIR}/${binary}"
            log_success "Installed: $binary"
        fi
    done
}

# Function: Install configurations
install_configs() {
    local extract_dir="$1"
    local config_src="${extract_dir}/config"

    if [[ -d "$config_src" ]]; then
        cp -r "$config_src"/* "$CONFIG_DIR/" || {
            log_error "Failed to install configurations"
            return 1
        }
        log_success "Configurations installed"
    fi
}

# Function: Update PATH if needed
update_path() {
    local shell_rc=""

    if [[ "$SHELL" == *"bash"* ]]; then
        shell_rc="$HOME/.bashrc"
    elif [[ "$SHELL" == *"zsh"* ]]; then
        shell_rc="$HOME/.zshrc"
    else
        return 0
    fi

    if [[ -f "$shell_rc" ]]; then
        if ! grep -q "$INSTALL_DIR" "$shell_rc"; then
            echo "export PATH=\"\$PATH:$INSTALL_DIR\"" >> "$shell_rc"
            log_info "Updated $shell_rc with $INSTALL_DIR"
        fi
    fi
}

# Function: Verify installation
verify_installation() {
    log_info "Verifying installation..."

    if command -v typedialog &>/dev/null; then
        local version
        version=$(typedialog --version 2>/dev/null || echo "unknown")
        log_success "TypeDialog installed: $version"
    else
        log_error "Installation verification failed"
        return 1
    fi
}

# Function: Main entry point
main() {
    log_info "TypeDialog Installation"
    log_info "========================"

    local platform
    platform=$(detect_platform) || return 1
    log_info "Detected platform: $platform"

    create_dirs || return 1

    local archive
    archive=$(download_release "$platform") || return 1

    local extract_dir
    extract_dir=$(extract_archive "$archive") || return 1
    trap 'rm -rf '"$extract_dir" EXIT

    install_binaries "$extract_dir" || return 1
    install_configs "$extract_dir" || return 1

    update_path

    verify_installation || return 1

    log_success "TypeDialog installation complete!"
    log_info "Install directory: $INSTALL_DIR"
    log_info "Config directory: $CONFIG_DIR"

    return 0
}

main "$@"
