#!/usr/bin/env bash
# refresh_app_hub — Pipeline: regenera icons + manifest del App Hub y reinicia el proceso
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REGISTRY_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

source "$SCRIPT_DIR/../infra/is_cpp_app_running_windows.sh"
source "$SCRIPT_DIR/../infra/launch_cpp_app_windows.sh"

PYTHON="${REGISTRY_ROOT}/python/.venv/bin/python3"
HUB_APP="app_hub_launcher"

refresh_app_hub() {
    local hub_dir="/mnt/c/Users/lucas/Desktop/apps/app_hub_launcher/local_files"
    local size=64
    local no_restart=0
    local style="white_duotone"

    # Parsear flags
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --hub-dir)
                hub_dir="$2"
                shift 2
                ;;
            --size)
                size="$2"
                shift 2
                ;;
            --no-restart)
                no_restart=1
                shift
                ;;
            --style)
                style="$2"
                shift 2
                ;;
            -*)
                echo "refresh_app_hub: flag desconocido: $1" >&2
                return 1
                ;;
            *)
                echo "refresh_app_hub: argumento inesperado: $1" >&2
                return 1
                ;;
        esac
    done

    local icons_dir="${hub_dir}/icons"
    local manifest_path="${hub_dir}/hub_manifest.tsv"

    # Paso 1: exportar PNGs de iconos
    echo "[1/4] Exporting PNG icons (size=${size}px) → ${icons_dir} ..."
    local icons_json
    icons_json=$(
        PYTHONPATH="${REGISTRY_ROOT}/python/functions" \
        FN_REGISTRY_ROOT="${REGISTRY_ROOT}" \
        "$PYTHON" \
            "${REGISTRY_ROOT}/python/functions/infra/export_hub_icons.py" \
            "$icons_dir" \
            --size "$size" \
            --registry-root "$REGISTRY_ROOT" \
            --style "$style"
    ) || {
        echo "ERROR [1/4]: export_hub_icons falló" >&2
        return 1
    }
    local icon_count
    icon_count=$(echo "$icons_json" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['count'])" 2>/dev/null || echo "?")
    echo "[1/4] PNG icons exported: ${icon_count}"

    # Paso 2: exportar TSV manifest
    echo "[2/4] Exporting manifest → ${manifest_path} ..."
    local manifest_json
    manifest_json=$(
        PYTHONPATH="${REGISTRY_ROOT}/python/functions" \
        FN_REGISTRY_ROOT="${REGISTRY_ROOT}" \
        "$PYTHON" \
            "${REGISTRY_ROOT}/python/functions/infra/export_hub_manifest.py" \
            "$manifest_path" \
            --registry-root "$REGISTRY_ROOT"
    ) || {
        echo "ERROR [2/4]: export_hub_manifest falló" >&2
        return 1
    }
    local manifest_count
    manifest_count=$(echo "$manifest_json" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['count'])" 2>/dev/null || echo "?")
    echo "[2/4] Manifest exported: ${manifest_count} rows"

    # Si --no-restart, terminar aqui
    if [[ $no_restart -eq 1 ]]; then
        echo "[3/4] Kill skipped (--no-restart)"
        echo "[4/4] Launch skipped (--no-restart)"
        echo "OK: app_hub refreshed (no-restart)"
        return 0
    fi

    # Paso 3: matar el hub si está corriendo
    local running=0
    if is_cpp_app_running_windows "$HUB_APP" >/dev/null 2>&1; then
        running=1
    fi

    if [[ $running -eq 1 ]]; then
        echo "[3/4] Hub running → killing ${HUB_APP}.exe ..."
        taskkill.exe /IM "${HUB_APP}.exe" /F >/dev/null 2>&1 || {
            echo "ERROR [3/4]: taskkill falló para ${HUB_APP}.exe" >&2
            return 1
        }
        # Pequeña pausa para que Windows libere el handle antes del relanzamiento
        sleep 1
        echo "[3/4] Hub running → killed"
    else
        echo "[3/4] Hub not running → skip kill"
    fi

    # Paso 4: relanzar el hub
    echo "[4/4] Launching ${HUB_APP} ..."
    if ! launch_cpp_app_windows "$HUB_APP"; then
        echo "ERROR [4/4]: launch_cpp_app_windows falló para '${HUB_APP}'" >&2
        return 1
    fi
    echo "[4/4] Hub launched"

    echo "OK: app_hub refreshed"
}

# Ejecutar si se llama directamente (fn run lo invoca como script)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    refresh_app_hub "$@"
fi
