#!/usr/bin/env bash

# ══════════════════════════════════════════════════════════════
#  Tralegraffe ROM Extractor — macOS Edition
#  Versione 26.04 — Copyright (c) 2026 Tralegraffe Software Solution
#  Licenza MIT
#  Decompressione ricorsiva archivi ZIP per collezioni ROM
# ══════════════════════════════════════════════════════════════

set -euo pipefail

# ── Colori e stili ──
RED="$(tput setaf 1)";   GREEN="$(tput setaf 2)";  YELLOW="$(tput setaf 3)"
BLUE="$(tput setaf 4)";  MAGENTA="$(tput setaf 5)"; CYAN="$(tput setaf 6)"
WHITE="$(tput setaf 7)"; BOLD="$(tput bold)";       DIM="$(tput dim)"
RESET="$(tput sgr0)"

# ══════════════════════════════════════════════════════════════
# ── SISTEMA DI LICENZE ──
# ══════════════════════════════════════════════════════════════
LICENSE_API="https://tralegraffe.it/license_api.php"
PRODUCT_CODE="UNZIP-MACOS"
APP_VERSION="26.04"
PLATFORM="macos"
LICENSE_FILE="$HOME/.unzip_license"

get_device_id() {
    local serial
    serial=$(ioreg -l | grep IOPlatformSerialNumber | sed 's/.*= "//;s/"//')
    echo "MAC-${serial:-UNKNOWN}"
}
DEVICE_ID=$(get_device_id)

save_license_key() { echo "$1" > "$LICENSE_FILE" && chmod 600 "$LICENSE_FILE"; }
load_license_key() { if [[ -f "$LICENSE_FILE" ]]; then cat "$LICENSE_FILE"; else echo ""; fi; }

license_api_call() {
    curl -s -m 15 -X POST -H "Content-Type: application/json" -d "$1" "$LICENSE_API" 2>/dev/null
}

validate_license() {
    local key="$1" response valid code message
    response=$(license_api_call "{\"action\":\"validate\",\"product_code\":\"$PRODUCT_CODE\",\"license_key\":\"$key\",\"device_id\":\"$DEVICE_ID\",\"app_version\":\"$APP_VERSION\",\"platform\":\"$PLATFORM\"}")
    [[ -z "$response" ]] && { echo "${YELLOW}  Impossibile contattare il server licenze.${RESET}"; exit 1; }
    valid=$(echo "$response" | grep -o '"valid" *: *[a-z]*' | head -1 | grep -o 'true\|false')
    code=$(echo "$response" | grep -o '"code" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    message=$(echo "$response" | grep -o '"message" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    if [[ "$valid" == "true" ]]; then
        echo "${GREEN}  ✅ Licenza lifetime valida.${RESET}"; return 0
    else
        case "$code" in
            invalid_key) echo "${RED}  ❌ Chiave non valida.${RESET}"; rm -f "$LICENSE_FILE" ;;
            suspended|revoked) echo "${RED}  ❌ Licenza $code. Contatta il supporto.${RESET}" ;;
            activation_limit_reached) echo "${RED}  ❌ Limite dispositivi raggiunto.${RESET}" ;;
            *) echo "${RED}  ❌ $message${RESET}" ;;
        esac; return 1
    fi
}

request_activation() {
    local name="$1" email="$2" response valid code issued_key message
    response=$(license_api_call "{\"action\":\"request_trial\",\"product_code\":\"$PRODUCT_CODE\",\"device_id\":\"$DEVICE_ID\",\"app_version\":\"$APP_VERSION\",\"platform\":\"$PLATFORM\",\"customer_name\":\"$name\",\"customer_email\":\"$email\"}")
    [[ -z "$response" ]] && { echo "${RED}  ❌ Server licenze non raggiungibile.${RESET}"; return 1; }
    valid=$(echo "$response" | grep -o '"valid" *: *[a-z]*' | head -1 | grep -o 'true\|false')
    code=$(echo "$response" | grep -o '"code" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    issued_key=$(echo "$response" | grep -o '"issued_license_key" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    message=$(echo "$response" | grep -o '"message" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    if [[ "$valid" == "true" && -n "$issued_key" ]]; then
        save_license_key "$issued_key"
        echo "${GREEN}  ✅ Attivato con successo! Licenza lifetime.${RESET}"; return 0
    elif [[ "$code" == "trial_active" && -n "$issued_key" ]]; then
        save_license_key "$issued_key"
        echo "${GREEN}  ✅ Gia attivato su questo dispositivo.${RESET}"; return 0
    else
        echo "${RED}  ❌ Attivazione fallita: $message${RESET}"; return 1
    fi
}

check_license() {
    echo "${DIM}  🔑 Verifica attivazione...${RESET}"
    local saved_key; saved_key=$(load_license_key)
    if [[ -n "$saved_key" ]]; then
        validate_license "$saved_key" && return 0
        saved_key=$(load_license_key)
    fi
    if [[ -z "$saved_key" ]]; then
        echo ""
        echo "${YELLOW}  Attivazione gratuita richiesta (una tantum).${RESET}"
        echo "${DIM}  Serve una connessione internet.${RESET}"
        echo ""
        read -rp "  Nome e Cognome: " act_name
        read -rp "  Email: " act_email
        [[ -z "$act_name" || -z "$act_email" ]] && { echo "${RED}  ❌ Nome e email obbligatori.${RESET}"; exit 1; }
        request_activation "$act_name" "$act_email" && return 0 || exit 1
    fi
}

check_license
echo ""
# ══════════════════════════════════════════════════════════════
# ── FINE SISTEMA DI LICENZE ──
# ══════════════════════════════════════════════════════════════

# ── Utilita ──
format_size() {
    local bytes=$1
    if (( bytes >= 1073741824 )); then
        printf '%.2f GB' "$(echo "scale=2; $bytes / 1073741824" | bc)"
    elif (( bytes >= 1048576 )); then
        printf '%.1f MB' "$(echo "scale=1; $bytes / 1048576" | bc)"
    elif (( bytes >= 1024 )); then
        printf '%.0f KB' "$(echo "scale=0; $bytes / 1024" | bc)"
    else
        printf '%d B' "$bytes"
    fi
}

format_duration() {
    local s="$1"
    (( s < 0 )) && s=0
    local h=$((s/3600)) m=$(((s%3600)/60)) sec=$((s%60))
    (( h > 0 )) && printf '%02d:%02d:%02d' "$h" "$m" "$sec" || printf '%02d:%02d' "$m" "$sec"
}

progress_bar() {
    local cur="$1" tot="$2" ts="$3" label="$4" w=40
    (( tot <= 0 )) && { printf '\r  %s' "$label"; return; }
    local now elapsed eta pct filled empty
    now=$(date +%s); elapsed=$((now - ts))
    (( cur > 0 )) && eta=$((elapsed * (tot - cur) / cur)) || eta=0
    pct=$((cur * 100 / tot)); filled=$((cur * w / tot)); empty=$((w - filled))
    local bar spaces
    printf -v bar '%*s' "$filled" ''; bar=${bar// /█}
    printf -v spaces '%*s' "$empty" ''; spaces=${spaces// /░}
    printf '\r  %s%s%s%s %3d%% %s(%d/%d)%s %s %s⏱ %s%s %s⏳ %s%s' \
        "$CYAN" "$bar" "$spaces" "$RESET" "$pct" \
        "$DIM" "$cur" "$tot" "$RESET" "$label" \
        "$DIM" "$(format_duration $elapsed)" "$RESET" \
        "$DIM" "$(format_duration $eta)" "$RESET"
}

# ── Banner ──
banner() {
    clear
    echo ""
    echo "${BOLD}${CYAN}  ╔══════════════════════════════════════════════════════╗${RESET}"
    echo "${BOLD}${CYAN}  ║${RESET}${BOLD}${WHITE}   🗜️  Tralegraffe ROM Extractor                v26.04 ${RESET}${BOLD}${CYAN}║${RESET}"
    echo "${BOLD}${CYAN}  ║${RESET}${DIM}      Decompressione collezioni ROM / retrocomputing  ${RESET}${BOLD}${CYAN}║${RESET}"
    echo "${BOLD}${CYAN}  ╚══════════════════════════════════════════════════════╝${RESET}"
    echo ""
}

# ── Selezione cartella (macOS nativo) ──
choose_folder() {
    TARGET_DIR=$(osascript <<'EOF'
        tell application "Finder"
            set theFolder to choose folder with prompt "Seleziona la cartella con gli archivi ZIP:"
            return POSIX path of theFolder
        end tell
EOF
    ) 2>/dev/null || TARGET_DIR=""
}

# ── Estrazione ricorsiva ──
do_unzip() {
    local dir="$1"
    local -a zip_files=()

    echo "${DIM}  Scansione archivi in corso...${RESET}"
    while IFS= read -r -d '' file; do
        zip_files+=("$file")
    done < <(find "$dir" -type f -iname "*.zip" -print0 2>/dev/null)

    local total=${#zip_files[@]}

    echo ""
    echo "  ${BOLD}${CYAN}📂 Cartella:${RESET} $dir"
    echo "  ${BOLD}${CYAN}📦 Archivi trovati:${RESET} $total"
    echo ""

    if (( total == 0 )); then
        echo "  ${YELLOW}Nessun file ZIP trovato nella cartella selezionata.${RESET}"
        echo ""
        read -rp "  Premi INVIO per tornare al menu..."
        return
    fi

    # Calcolo dimensione totale compressa
    local total_compressed=0
    for file in "${zip_files[@]}"; do
        local fsize
        fsize=$(stat -f%z "$file" 2>/dev/null || echo 0)
        total_compressed=$((total_compressed + fsize))
    done
    echo "  ${DIM}Dimensione compressa totale: $(format_size $total_compressed)${RESET}"
    echo ""

    local start_ts current=0 ok_count=0 err_count=0 freed=0
    start_ts=$(date +%s)

    for file in "${zip_files[@]}"; do
        current=$((current + 1))
        local zipdir file_name fsize
        zipdir="$(dirname "$file")"
        file_name="$(basename "$file")"
        fsize=$(stat -f%z "$file" 2>/dev/null || echo 0)

        progress_bar "$current" "$total" "$start_ts" "$file_name"
        echo ""

        if unzip -oq "$file" -d "$zipdir" 2>/dev/null; then
            rm -f "$file"
            ok_count=$((ok_count + 1))
            freed=$((freed + fsize))
        else
            echo "  ${RED}⚠ Errore:${RESET} $file_name"
            err_count=$((err_count + 1))
        fi
    done

    local end_ts elapsed
    end_ts=$(date +%s)
    elapsed=$((end_ts - start_ts))

    echo ""
    echo "  ${BOLD}${CYAN}══════════════ RIEPILOGO ══════════════${RESET}"
    echo "  ${GREEN}✅ Estratti:${RESET}   $ok_count"
    echo "  ${RED}❌ Errori:${RESET}     $err_count"
    echo "  ${CYAN}📦 Totale:${RESET}     $total"
    echo "  ${MAGENTA}💾 Spazio liberato:${RESET} $(format_size $freed)"
    echo "  ${BLUE}⏱  Tempo:${RESET}      $(format_duration $elapsed)"
    echo "  ${BOLD}${CYAN}═══════════════════════════════════════${RESET}"
    echo ""
    read -rp "  Premi INVIO per tornare al menu..."
}

# ── Menu principale ──
menu() {
    while true; do
        banner
        echo "  ${BOLD}${WHITE}Operazioni disponibili:${RESET}"
        echo ""
        echo "  ${BOLD}${YELLOW}  1)${RESET} 📂 Seleziona cartella e decomprimi tutti i file ZIP"
        echo "  ${BOLD}${YELLOW}  2)${RESET} 📋 Mostra info sul software"
        echo "  ${BOLD}${YELLOW}  3)${RESET} 🚪 Esci"
        echo ""
        echo -n "  ${BOLD}${WHITE}Scelta [1-3]:${RESET} "
        read -r choice

        case "$choice" in
            1)
                choose_folder
                if [[ -d "${TARGET_DIR:-}" ]]; then
                    do_unzip "$TARGET_DIR"
                else
                    echo "  ${RED}Nessuna cartella selezionata.${RESET}"
                    sleep 1.5
                fi
                ;;
            2)
                echo ""
                echo "  ${BOLD}${CYAN}Tralegraffe ROM Extractor${RESET} v${APP_VERSION}"
                echo "  ${DIM}Copyright (c) 2026 Tralegraffe Software Solution${RESET}"
                echo "  ${DIM}Licenza MIT — Piattaforma: macOS${RESET}"
                echo "  ${DIM}Device ID: ${DEVICE_ID}${RESET}"
                echo ""
                read -rp "  Premi INVIO per tornare al menu..."
                ;;
            3)
                echo ""
                echo "  ${BOLD}${YELLOW}Grazie per aver usato Tralegraffe ROM Extractor.${RESET}"
                echo ""
                exit 0
                ;;
            *)
                echo "  ${RED}Scelta non valida.${RESET}"
                sleep 1
                ;;
        esac
    done
}

menu
