#!/bin/bash
set -e

# ------------------------
# Cores
# ------------------------
RESET="\033[0m"
BOLD="\033[1m"

RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
CYAN="\033[36m"
MAGENTA="\033[35m"
GRAY="\033[90m"

timestamp() {
    date +"%H:%M:%S"
}

log() {
    local level="$1"
    local color="$2"
    shift 2
    echo -e "${GRAY}[$(timestamp)]${RESET} ${color}${level}${RESET} $*"
}

log_info()  { log "[INFO]"  "$BLUE" "$@"; }
log_ok()    { log "[OK]"    "$GREEN" "$@"; }
log_warn()  { log "[WARN]"  "$YELLOW" "$@"; }
log_error() { log "[ERROR]" "$RED" "$@"; }
log_cmd()   { log "[CMD]"   "$CYAN" "${BOLD}$*${RESET}"; }
log_debug() { log "[DBG]"   "$GRAY" "$@"; }

# ------------------------
# Banner
# ------------------------
print_banner() {
echo -e "${MAGENTA}${BOLD}"
cat << "EOF"
 _____             _____     _   
|     |___ ___ _ _| __  |___| |_ 
| | | | .'|   | | | __ -| . |  _|
|_|_|_|__,|_|_|_  |_____|___|_|  
              |___|              

website: www.mlplovers.com.br/manybot
repo: github.com/synt-xerror/manybot

A Amizade é Mágica!

EOF
echo -e "${RESET}"
}

print_banner
log_info "Inicializando setup..."

# ------------------------
# Executar comandos
# ------------------------
run_cmd() {
    log_cmd "$*"
    "$@"
    log_ok "Comando finalizado: $1"
}

# ------------------------
# Download
# ------------------------
download_file() {
    local url="$1"
    local dest="$2"

    log_debug "download_file(url=$url, dest=$dest)"

    if [[ -f "$dest" ]]; then
        log_warn "Arquivo já existe: $dest"
        return
    fi

    log_info "Baixando $url"
    log_debug "Destino: $dest"

    if command -v curl >/dev/null 2>&1; then
        log_debug "Downloader: curl"
        curl -L "$url" -o "$dest"
    elif command -v wget >/dev/null 2>&1; then
        log_debug "Downloader: wget"
        wget "$url" -O "$dest"
    else
        log_error "curl ou wget não encontrados"
        exit 1
    fi

    chmod +x "$dest" 2>/dev/null || true
    log_ok "Arquivo pronto: $dest"
}

# ------------------------
# Detectar plataforma
# ------------------------
log_info "Detectando plataforma"

UNAME="$(uname -s)"
ARCH="$(uname -m)"

PLATFORM=""
case "$UNAME" in
    Linux*)   PLATFORM="linux";;
    Darwin*)  PLATFORM="mac";;
    MINGW*|MSYS*|CYGWIN*) PLATFORM="win";;
    *)        PLATFORM="unknown";;
esac

log_info "Sistema: $UNAME"
log_info "Arquitetura: $ARCH"
log_info "Plataforma: $PLATFORM"

# ------------------------
# Informações do ambiente
# ------------------------
log_info "Verificando ambiente"

log_debug "Node: $(node -v 2>/dev/null || echo 'não encontrado')"
log_debug "npm:  $(npm -v 2>/dev/null || echo 'não encontrado')"
log_debug "PREFIX: ${PREFIX:-<vazio>}"

# ------------------------
# Termux
# ------------------------
install_deps() {
    local packages=("$@")

    for pkg in "${packages[@]}"; do
        if ! dpkg -s "$pkg" >/dev/null 2>&1; then
            log_warn "$pkg não encontrado, instalando"
            run_cmd pkg install -y "$pkg"
        else
            log_ok "$pkg já instalado"
        fi
    done
}

if [[ "$PREFIX" == *"com.termux"* ]]; then
    log_info "Ambiente Termux detectado"

    deps=(
        chromium
    )

    install_deps "${deps[@]}"
fi

# ------------------------
# Setup npm
# ------------------------
log_info "Instalando dependências npm"

export PUPPETEER_SKIP_DOWNLOAD=1
run_cmd npm install

# ------------------------
# Diretórios
# ------------------------
log_info "Preparando diretórios"
mkdir -p bin
log_debug "Diretório bin garantido"

# ------------------------
# Arquivos por plataforma
# ------------------------
log_info "Selecionando dependências binárias"

files=()
if [[ "$PLATFORM" == "win" ]]; then
    log_debug "Usando binários Windows"
    files=(
        "https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe bin/yt-dlp.exe"
        "https://github.com/synt-xerror/manybot/releases/download/dependencies/ffmpeg.exe bin/ffmpeg.exe"
    )
else
    log_debug "Usando binários Unix"
    files=(
        "https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp bin/yt-dlp"
        "https://github.com/synt-xerror/manybot/releases/download/dependencies/ffmpeg bin/ffmpeg"
    )
fi

log_debug "Total de arquivos para baixar: ${#files[@]}"

# ------------------------
# Download
# ------------------------
for file in "${files[@]}"; do
    url="${file%% *}"
    dest="${file##* }"

    log_info "Processando dependência"
    download_file "$url" "$dest"
done

log_ok "Setup concluído com sucesso"