#!/bin/bash
# =============================================
# NEBULA GAME UPDATER - VPS (Hugging Face Direct)
# =============================================
# Aktualizuje gry na serwerze z HuggingFace
# =============================================

set -e

# KOLORY
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# =============================================
# KONFIGURACJA
# =============================================
HF_USER="qwdqdqwe"
HF_REPO="system-gier"
HF_API_URL="https://huggingface.co/api/datasets/$HF_USER/$HF_REPO"
HF_RAW_URL="https://huggingface.co/datasets/$HF_USER/$HF_REPO/resolve/main"

GAMES_DIR="/var/www/launcher-server/games"
SYS_GAME_FILE="/var/www/launcher-server/sys/SYS_Game.json"
TEMP_DIR="/tmp/nebula-update"

# =============================================
# FUNKCJE
# =============================================

print_header() {
    clear
    echo -e "${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║                                                              ║${NC}"
    echo -e "${CYAN}║           🌌 NEBULA GAME UPDATER v2.0                       ║${NC}"
    echo -e "${CYAN}║           📦 Hugging Face Direct                           ║${NC}"
    echo -e "${CYAN}║                                                              ║${NC}"
    echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

list_games() {
    echo -e "${YELLOW}📋 Pobieranie listy gier z Hugging Face...${NC}"
    echo ""
    
    # Pobierz listę plików z Hugging Face API
    local response=$(curl -s "$HF_API_URL")
    
    if [ -z "$response" ]; then
        echo -e "${RED}❌ Nie można połączyć z Hugging Face API${NC}"
        return 1
    fi
    
    # Wyciągnij tylko pliki .zip
    local games=$(echo "$response" | jq -r '.siblings[].rfilename' 2>/dev/null | grep '\.zip$' | sed 's/\.zip$//')
    
    if [ -z "$games" ]; then
        echo -e "${RED}❌ Nie znaleziono żadnych gier w repozytorium${NC}"
        return 1
    fi
    
    # Wyświetl z numerami
    local i=1
    while IFS= read -r game; do
        # Pobierz rozmiar dla wyświetlenia
        local size=$(echo "$response" | jq -r --arg game "$game.zip" '.siblings[] | select(.rfilename == $game) | .size' 2>/dev/null)
        local size_mb=$(echo "scale=2; $size / 1048576" | bc 2>/dev/null || echo "?")
        
        printf "  ${CYAN}%2d.${NC} %-30s ${YELLOW}%8s MB${NC}\n" "$i" "$game" "$size_mb"
        ((i++))
    done <<< "$games"
    
    echo ""
    echo -e "${YELLOW}  A. Aktualizuj WSZYSTKIE gry${NC}"
    echo -e "${YELLOW}  Q. Wyjście${NC}"
    echo ""
    
    # Zapisz listę gier do pliku tymczasowego
    echo "$games" > "$TEMP_DIR/games_list.txt"
}

get_game_info() {
    local game_id="$1"
    
    # Pobierz informacje o konkretnym pliku
    local file_info=$(curl -s "$HF_API_URL" | jq --arg game "$game_id.zip" '.siblings[] | select(.rfilename == $game)')
    
    if [ -z "$file_info" ] || [ "$file_info" == "null" ]; then
        return 1
    fi
    
    local size=$(echo "$file_info" | jq -r '.size // 0')
    local size_mb=$(echo "scale=2; $size / 1048576" | bc)
    local etag=$(echo "$file_info" | jq -r '.rfilename' | md5sum | cut -d' ' -f1)
    
    # Generuj URL pobierania (bezpośrednio z Hugging Face)
    local download_url="$HF_RAW_URL/$game_id.zip"
    
    echo "$size|$size_mb|$download_url|$etag"
}

download_game() {
    local game_id="$1"
    local download_url="$2"
    local output_file="$TEMP_DIR/$game_id.zip"
    
    echo -e "${YELLOW}📥 Pobieranie: $game_id${NC}"
    echo -e "${BLUE}   Źródło: $HF_USER/$HF_REPO${NC}"
    echo -e "${BLUE}   Plik: $output_file${NC}"
    echo ""
    
    # Pobierz z progresem (użyj curl z --progress-bar)
    curl -L --progress-bar -o "$output_file" "$download_url"
    
    if [ ! -f "$output_file" ] || [ ! -s "$output_file" ]; then
        echo -e "${RED}❌ Błąd pobierania${NC}"
        return 1
    fi
    
    local file_size=$(stat -f%z "$output_file" 2>/dev/null || stat -c%s "$output_file" 2>/dev/null)
    local file_size_mb=$(echo "scale=2; $file_size / 1048576" | bc)
    echo -e "${GREEN}✅ Pobrano: ${file_size_mb} MB${NC}"
    echo ""
}

extract_game() {
    local game_id="$1"
    local zip_file="$TEMP_DIR/$game_id.zip"
    local extract_dir="$GAMES_DIR/$game_id"
    
    echo -e "${YELLOW}📦 Rozpakowywanie: $game_id${NC}"
    
    # Usuń stary katalog
    if [ -d "$extract_dir" ]; then
        echo -e "${BLUE}   Usuwanie starej wersji...${NC}"
        rm -rf "$extract_dir"
    fi
    
    # Stwórz katalog
    mkdir -p "$extract_dir"
    
    # Rozpakuj
    unzip -q "$zip_file" -d "$extract_dir"
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ Rozpakowano do: $extract_dir${NC}"
        return 0
    else
        echo -e "${RED}❌ Błąd rozpakowywania${NC}"
        return 1
    fi
}

update_sys_game() {
    local game_id="$1"
    local version="$2"
    local size_mb="$3"
    local checksum="$4"
    local game_name="$5"
    
    echo -e "${YELLOW}📝 Aktualizacja SYS_Game.json...${NC}"
    
    # Utwórz tymczasowy plik JSON
    local tmp_json="$TEMP_DIR/tmp_sys.json"
    
    # Jeśli plik istnieje, użyj go
    if [ -f "$SYS_GAME_FILE" ]; then
        cp "$SYS_GAME_FILE" "$tmp_json"
    else
        echo '{"games": {}, "last_update": null, "total_games": 0, "total_size_mb": 0}' > "$tmp_json"
    fi
    
    # Aktualizuj JSON (użyj jq)
    jq --arg id "$game_id" \
       --arg name "$game_name" \
       --arg version "$version" \
       --arg size_mb "$size_mb" \
       --arg checksum "$checksum" \
       --arg timestamp "$(date -Iseconds)" \
       --arg url "$HF_RAW_URL/$id.zip" \
       '.games[$id] = {
           "game_id": $id,
           "game_name": $name,
           "version": $version,
           "size_mb": ($size_mb | tonumber),
           "checksum": $checksum,
           "downloadUrl": $url,
           "last_updated": $timestamp
       }' "$tmp_json" > "$tmp_json.2"
    
    mv "$tmp_json.2" "$tmp_json"
    
    # Aktualizuj total
    jq '.total_games = (.games | keys | length)' "$tmp_json" > "$tmp_json.2"
    mv "$tmp_json.2" "$tmp_json"
    
    jq '.total_size_mb = ([.games[] | .size_mb] | add // 0)' "$tmp_json" > "$tmp_json.2"
    mv "$tmp_json.2" "$tmp_json"
    
    jq --arg timestamp "$(date -Iseconds)" '.last_update = $timestamp' "$tmp_json" > "$tmp_json.2"
    mv "$tmp_json.2" "$tmp_json"
    
    # Zapisz
    mkdir -p "$(dirname "$SYS_GAME_FILE")"
    cp "$tmp_json" "$SYS_GAME_FILE"
    
    echo -e "${GREEN}✅ SYS_Game.json zaktualizowany${NC}"
}

cleanup() {
    echo -e "${YELLOW}🧹 Czyszczenie...${NC}"
    rm -rf "$TEMP_DIR"
}

# =============================================
# GŁÓWNA FUNKCJA
# =============================================

main() {
    # Stwórz katalog tymczasowy
    mkdir -p "$TEMP_DIR"
    
    # Wyświetl nagłówek
    print_header
    
    # Sprawdź czy jq jest zainstalowany
    if ! command -v jq &> /dev/null; then
        echo -e "${RED}❌ jq nie jest zainstalowany!${NC}"
        echo -e "${YELLOW}   sudo apt-get install jq${NC}"
        exit 1
    fi
    
    # Sprawdź czy curl jest zainstalowany
    if ! command -v curl &> /dev/null; then
        echo -e "${RED}❌ curl nie jest zainstalowany!${NC}"
        echo -e "${YELLOW}   sudo apt-get install curl${NC}"
        exit 1
    fi
    
    # Sprawdź czy unzip jest zainstalowany
    if ! command -v unzip &> /dev/null; then
        echo -e "${RED}❌ unzip nie jest zainstalowany!${NC}"
        echo -e "${YELLOW}   sudo apt-get install unzip${NC}"
        exit 1
    fi
    
    # Wyświetl gry
    list_games
    
    # Pobierz wybór
    echo -ne "${CYAN}👉 Wybierz opcję (numer, A, Q): ${NC}"
    read choice
    
    case "$choice" in
        q|Q)
            echo -e "${YELLOW}👋 Wyjście${NC}"
            cleanup
            exit 0
            ;;
        a|A)
            echo -e "${YELLOW}🔄 Aktualizacja WSZYSTKICH gier...${NC}"
            
            local games=$(cat "$TEMP_DIR/games_list.txt")
            local total=0
            local success=0
            local failed=0
            
            while IFS= read -r game_id; do
                ((total++))
                echo ""
                echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
                echo -e "${MAGENTA}📦 [$total] Aktualizacja: $game_id${NC}"
                echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
                echo ""
                
                if update_single_game "$game_id"; then
                    ((success++))
                else
                    ((failed++))
                fi
                
                echo ""
            done <<< "$games"
            
            echo ""
            echo -e "${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
            echo -e "${CYAN}║                       📊 PODSUMOWANIE                       ║${NC}"
            echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
            echo -e "${GREEN}✅ Udanych: $success${NC}"
            echo -e "${RED}❌ Nieudanych: $failed${NC}"
            echo -e "${YELLOW}📦 Razem: $total${NC}"
            ;;
        *)
            # Numer - pojedyncza gra
            if ! [[ "$choice" =~ ^[0-9]+$ ]]; then
                echo -e "${RED}❌ Nieprawidłowy wybór${NC}"
                cleanup
                exit 1
            fi
            
            local game_id=$(sed -n "${choice}p" "$TEMP_DIR/games_list.txt" 2>/dev/null)
            
            if [ -z "$game_id" ]; then
                echo -e "${RED}❌ Nieprawidłowy numer${NC}"
                cleanup
                exit 1
            fi
            
            echo ""
            echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
            echo -e "${MAGENTA}📦 Aktualizacja: $game_id${NC}"
            echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
            echo ""
            
            update_single_game "$game_id"
            ;;
    esac
    
    # Czyszczenie
    cleanup
    
    echo ""
    echo -e "${GREEN}✅ Zakończono!${NC}"
    exit 0
}

update_single_game() {
    local game_id="$1"
    
    # Pobierz informacje
    local info=$(get_game_info "$game_id")
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ Nie znaleziono gry: $game_id${NC}"
        return 1
    fi
    
    # Parsuj informacje
    local size=$(echo "$info" | cut -d'|' -f1)
    local size_mb=$(echo "$info" | cut -d'|' -f2)
    local download_url=$(echo "$info" | cut -d'|' -f3)
    local checksum=$(echo "$info" | cut -d'|' -f4)
    
    # Generuj wersję z daty
    local version=$(date +"%Y.%m.%d")
    
    # Formatuj nazwę gry
    local game_name=$(echo "$game_id" | sed 's/_/ /g' | sed 's/\b\(.\)/\u\1/g')
    
    echo -e "${WHITE}📊 Informacje:${NC}"
    echo -e "   Nazwa: ${GREEN}$game_name${NC}"
    echo -e "   Rozmiar: ${YELLOW}$size_mb MB${NC}"
    echo -e "   Wersja: ${CYAN}$version${NC}"
    echo -e "   URL: ${BLUE}$download_url${NC}"
    echo ""
    
    # Pobierz
    if ! download_game "$game_id" "$download_url"; then
        return 1
    fi
    
    # Rozpakuj
    if ! extract_game "$game_id"; then
        return 1
    fi
    
    # Aktualizuj SYS_Game.json
    update_sys_game "$game_id" "$version" "$size_mb" "$checksum" "$game_name"
    
    echo -e "${GREEN}✅ $game_name zaktualizowany!${NC}"
    return 0
}

# =============================================
# URUCHOMIENIE
# =============================================
main "$@"
