#!/bin/bash

# ============================================
#   Navigator Code v1.0.0 — Установка для macOS
# ============================================
#
# Использование:
#   chmod +x install-macos.sh
#   ./install-macos.sh
#
# Что делает:
#   1. Проверяет/устанавливает Node.js 18+
#   2. Копирует приложение в ~/.local/share/navicode/
#   3. Создаёт команды navicode и navigator-web в ~/.local/bin/
#   4. Добавляет ~/.local/bin в PATH

set -euo pipefail

# ============================================
# Цвета
# ============================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

info()    { echo -e "${BLUE}  ℹ  ${NC}$1"; }
ok()      { echo -e "${GREEN}  ✓  ${NC}$1"; }
warn()    { echo -e "${YELLOW}  ⚠  ${NC}$1"; }
err()     { echo -e "${RED}  ✗  ${NC}$1"; }

# ============================================
# Переменные
# ============================================
APP_NAME="navigator"
APP_VERSION="1.0.0"
INSTALL_DIR="${HOME}/.local/share/${APP_NAME}"
BIN_DIR="${HOME}/.local/bin"
NODE_FULL_VERSION="20.18.1"

# Определяем архитектуру
ARCH=$(uname -m)
case "${ARCH}" in
    x86_64)  NODE_ARCH="x64" ;;
    arm64)   NODE_ARCH="arm64" ;;
    *)
        err "Неподдерживаемая архитектура: ${ARCH}"
        exit 1
        ;;
esac

# ============================================
# Заголовок
# ============================================
echo ""
echo -e "${BOLD}============================================${NC}"
echo -e "${BOLD}  Navigator Code v${APP_VERSION} — Установка${NC}"
echo -e "${BOLD}============================================${NC}"
echo ""
info "Система: macOS $(sw_vers -productVersion 2>/dev/null || echo 'unknown')"
info "Архитектура: ${ARCH} (${NODE_ARCH})"
info "Каталог установки: ${INSTALL_DIR}"
echo ""

# ============================================
# Директория скрипта
# ============================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [[ ! -f "${SCRIPT_DIR}/app/dist/cli.js" ]]; then
    err "Не найден файл app/dist/cli.js рядом со скриптом"
    exit 1
fi

# ============================================
# Скачивание файла
# ============================================
download_file() {
    local url="$1"
    local dest="$2"
    curl -fSL --progress-bar --connect-timeout 15 --max-time 120 "${url}" -o "${dest}"
}

# ============================================
# Проверка Node.js
# ============================================
check_node() {
    # Портативный Node.js из предыдущей установки
    local node_dir="${INSTALL_DIR}/node"
    if [[ -x "${node_dir}/bin/node" ]]; then
        if "${node_dir}/bin/node" -e "process.exit(0)" 2>/dev/null; then
            local ver
            ver=$("${node_dir}/bin/node" -v | sed 's/v//' | cut -d. -f1)
            if [[ "${ver}" -ge 18 ]]; then
                ok "Портативный Node.js $("${node_dir}/bin/node" -v) уже установлен"
                NODE_BIN="${node_dir}/bin/node"
                return 0
            else
                warn "Портативный Node.js устарел (нужен >= 18), переустанавливаем..."
                rm -rf "${node_dir}"
            fi
        else
            rm -rf "${node_dir}"
        fi
    fi

    # Системный Node.js (brew, nvm, etc.)
    if command -v node &>/dev/null; then
        if node -e "process.exit(0)" 2>/dev/null; then
            local ver
            ver=$(node -v | sed 's/v//' | cut -d. -f1)
            if [[ "${ver}" -ge 18 ]]; then
                ok "Node.js $(node -v) уже установлен"
                NODE_BIN="$(command -v node)"
                return 0
            else
                warn "Node.js $(node -v) устарел (нужен >= 18)"
                return 1
            fi
        fi
    fi
    return 1
}

# ============================================
# Установка Node.js
# ============================================
install_node() {
    local node_dir="${INSTALL_DIR}/node"

    if [[ -d "${node_dir}" ]]; then
        rm -rf "${node_dir}"
    fi

    local url="https://nodejs.org/dist/v${NODE_FULL_VERSION}/node-v${NODE_FULL_VERSION}-darwin-${NODE_ARCH}.tar.gz"
    local tmp_file
    tmp_file=$(mktemp /tmp/node-XXXXXX.tar.gz)

    info "Скачивание Node.js v${NODE_FULL_VERSION} для ${NODE_ARCH}..."

    if download_file "${url}" "${tmp_file}"; then
        info "Распаковка..."
        mkdir -p "${node_dir}"
        tar -xzf "${tmp_file}" -C "${node_dir}" --strip-components=1
        rm -f "${tmp_file}"

        NODE_BIN="${node_dir}/bin/node"
        chmod +x "${NODE_BIN}"

        if "${NODE_BIN}" -e "process.exit(0)" 2>/dev/null; then
            ok "Node.js $("${NODE_BIN}" -v) установлен"
            return 0
        else
            err "Node.js не запускается"
            rm -rf "${node_dir}"
        fi
    else
        err "Не удалось скачать Node.js"
        rm -f "${tmp_file}"
    fi

    err ""
    err "Установите Node.js 18+ вручную:"
    err "  brew install node"
    err "  # или: https://nodejs.org/en/download"
    err "Затем запустите этот скрипт повторно."
    exit 1
}

# ============================================
# Установка приложения
# ============================================
install_app() {
    info "Установка Navigator Code..."

    mkdir -p "${INSTALL_DIR}/app/dist"
    mkdir -p "${INSTALL_DIR}/app/webapp/public"

    cp -r "${SCRIPT_DIR}/app/dist/"* "${INSTALL_DIR}/app/dist/"
    cp "${SCRIPT_DIR}/app/package.json" "${INSTALL_DIR}/app/" 2>/dev/null || true
    cp -r "${SCRIPT_DIR}/app/webapp/"* "${INSTALL_DIR}/app/webapp/" 2>/dev/null || true
    if [[ -d "${SCRIPT_DIR}/app/node_modules" ]]; then
        mkdir -p "${INSTALL_DIR}/app/node_modules"
        cp -r "${SCRIPT_DIR}/app/node_modules/"* "${INSTALL_DIR}/app/node_modules/"
    fi

    ok "Приложение установлено в ${INSTALL_DIR}/app/"
}

# ============================================
# Создание лаунчеров
# ============================================
create_launcher() {
    mkdir -p "${BIN_DIR}"

    # CLI лаунчер
    cat > "${BIN_DIR}/${APP_NAME}" <<LAUNCHER
#!/bin/bash
NODE_BIN="${NODE_BIN}"
APP="${INSTALL_DIR}/app/dist/cli.js"
if [[ ! -x "\${NODE_BIN}" ]]; then
    NODE_BIN=\$(command -v node 2>/dev/null || true)
    if [[ -z "\${NODE_BIN}" ]]; then
        echo "Ошибка: Node.js не найден. Установите: brew install node"
        exit 1
    fi
fi
exec "\${NODE_BIN}" "\${APP}" "\$@"
LAUNCHER
    chmod +x "${BIN_DIR}/${APP_NAME}"
    ok "Команда '${APP_NAME}' создана"

    # Web GUI лаунчер с поддержкой app-режима через Chromium-подобный браузер
    cat > "${BIN_DIR}/${APP_NAME}-web" <<LAUNCHER
#!/bin/bash
# Navigator Code Web GUI лаунчер.
# Использование:
#   navigator-web                 # домашняя папка
#   navigator-web /path/to/proj   # конкретный каталог

NODE_BIN="${NODE_BIN}"
SERVER="${INSTALL_DIR}/app/webapp/server.js"
PORT=\${NAVIGATOR_PORT:-3100}

if [[ ! -x "\${NODE_BIN}" ]]; then
    NODE_BIN=\$(command -v node 2>/dev/null || true)
    if [[ -z "\${NODE_BIN}" ]]; then
        echo "Ошибка: Node.js не найден. Установите: brew install node"
        exit 1
    fi
fi

TARGET_PATH="\${1:-}"
if [[ -z "\${TARGET_PATH}" ]] && [[ "\${PWD}" != "\${HOME}" ]]; then
    TARGET_PATH="\${PWD}"
fi

urlencode() {
    local s="\$1" out="" c i
    for (( i=0; i<\${#s}; i++ )); do
        c="\${s:i:1}"
        case "\$c" in
            [a-zA-Z0-9._~/-]) out+="\$c" ;;
            *) printf -v c '%%%02X' "'\$c"; out+="\$c" ;;
        esac
    done
    printf '%s' "\$out"
}
URL="http://localhost:\${PORT}/?app=1"
if [[ -n "\${TARGET_PATH}" ]]; then
    URL="\${URL}&path=\$(urlencode "\${TARGET_PATH}")"
fi

echo ""
echo "  Navigator Code Web Interface"
echo "  URL: \${URL}"
echo ""

# Ищем Chromium-подобный браузер для app-режима (окно без вкладок)
find_chromium_app() {
    local paths=(
        "/Applications/Google Chrome.app"
        "/Applications/Chromium.app"
        "/Applications/Microsoft Edge.app"
        "/Applications/Brave Browser.app"
        "/Applications/Vivaldi.app"
    )
    for p in "\${paths[@]}"; do
        [[ -d "\$p" ]] && { printf '%s' "\$p"; return 0; }
    done
    return 1
}

open_browser() {
    sleep 1
    local app
    if app=\$(find_chromium_app); then
        open -n -a "\$app" --args --app="\${URL}"
    else
        open "\${URL}"
    fi
}
open_browser &

exec "\${NODE_BIN}" "\${SERVER}"
LAUNCHER
    chmod +x "${BIN_DIR}/${APP_NAME}-web"
    ok "Команда '${APP_NAME}-web' создана"

    # Алиасы: navicode, nav → navigator
    ln -sf "${BIN_DIR}/${APP_NAME}" "${BIN_DIR}/navicode"
    ln -sf "${BIN_DIR}/${APP_NAME}" "${BIN_DIR}/nav"
    ok "Алиасы: navicode, nav → ${APP_NAME}"
}

# ============================================
# Finder Quick Action (сервис «Открыть в Navigator Code»)
# ============================================
# Создаёт Automator workflow в ~/Library/Services/, чтобы в Finder
# правый клик по папке показывал пункт «Открыть в Navigator Code».
create_finder_service() {
    local services_dir="${HOME}/Library/Services"
    mkdir -p "${services_dir}"

    local wf_dir="${services_dir}/Открыть в Navigator Code.workflow"
    rm -rf "${wf_dir}"
    mkdir -p "${wf_dir}/Contents"

    cat > "${wf_dir}/Contents/Info.plist" <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>NSServices</key>
  <array>
    <dict>
      <key>NSMenuItem</key>
      <dict>
        <key>default</key>
        <string>Открыть в Navigator Code</string>
      </dict>
      <key>NSMessage</key>
      <string>runWorkflowAsService</string>
      <key>NSRequiredContext</key>
      <dict>
        <key>NSApplicationIdentifier</key>
        <string>com.apple.finder</string>
      </dict>
      <key>NSSendFileTypes</key>
      <array>
        <string>public.folder</string>
      </array>
    </dict>
  </array>
</dict>
</plist>
PLIST

    cat > "${wf_dir}/Contents/document.wflow" <<WFLOW
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>AMApplicationBuild</key><string>512</string>
  <key>AMApplicationVersion</key><string>2.10</string>
  <key>AMDocumentVersion</key><string>2</string>
  <key>actions</key>
  <array>
    <dict>
      <key>action</key>
      <dict>
        <key>AMAccepts</key>
        <dict>
          <key>Container</key><string>List</string>
          <key>Optional</key><true/>
          <key>Types</key><array><string>com.apple.cocoa.string</string></array>
        </dict>
        <key>AMActionVersion</key><string>2.0.3</string>
        <key>AMParameterProperties</key>
        <dict>
          <key>COMMAND_STRING</key><dict/>
          <key>CheckedForUserDefaultShell</key><dict/>
          <key>inputMethod</key><dict/>
          <key>shell</key><dict/>
          <key>source</key><dict/>
        </dict>
        <key>ActionBundlePath</key><string>/System/Library/Automator/Run Shell Script.action</string>
        <key>ActionName</key><string>Run Shell Script</string>
        <key>ActionParameters</key>
        <dict>
          <key>COMMAND_STRING</key><string>p="\${1}"
[ -d "\$p" ] &amp;&amp; "${BIN_DIR}/${APP_NAME}-web" "\$p"</string>
          <key>inputMethod</key><integer>1</integer>
          <key>shell</key><string>/bin/bash</string>
          <key>source</key><string></string>
        </dict>
        <key>BundleIdentifier</key><string>com.apple.RunShellScript</string>
        <key>CFBundleVersion</key><string>2.0.3</string>
        <key>CanShowSelectedItemsWhenRun</key><false/>
        <key>CanShowWhenRun</key><true/>
        <key>Category</key><array><string>AMCategoryUtilities</string></array>
        <key>Class Name</key><string>RunShellScriptAction</string>
        <key>InputUUID</key><string>1D1F5A3A-1111-2222-3333-444444444444</string>
        <key>Keywords</key><array><string>Shell</string><string>Script</string><string>Command</string></array>
        <key>OutputUUID</key><string>2D1F5A3A-5555-6666-7777-888888888888</string>
        <key>UUID</key><string>3D1F5A3A-9999-AAAA-BBBB-CCCCCCCCCCCC</string>
      </dict>
    </dict>
  </array>
  <key>connectors</key><dict/>
  <key>workflowMetaData</key>
  <dict>
    <key>serviceApplicationBundleID</key><string>com.apple.finder</string>
    <key>serviceApplicationPath</key><string>/System/Library/CoreServices/Finder.app</string>
    <key>serviceInputTypeIdentifier</key><string>com.apple.Automator.fileSystemObject.folder</string>
    <key>serviceOutputTypeIdentifier</key><string>com.apple.Automator.nothing</string>
    <key>serviceProcessesInput</key><integer>0</integer>
    <key>systemImageName</key><string>NSActionTemplate</string>
    <key>useAutomaticInputType</key><integer>0</integer>
    <key>workflowTypeIdentifier</key><string>com.apple.Automator.servicesMenu</string>
  </dict>
</dict>
</plist>
WFLOW

    # Обновляем кэш сервисов
    /System/Library/CoreServices/pbs -update 2>/dev/null || true
    ok "Finder: пункт «Открыть в Navigator Code» добавлен (правый клик по папке → Службы)"
}

# ============================================
# PATH
# ============================================
ensure_path() {
    if echo "${PATH}" | tr ':' '\n' | grep -qx "${BIN_DIR}"; then
        return 0
    fi

    local shell_name
    shell_name=$(basename "${SHELL}")
    local profile=""

    case "${shell_name}" in
        bash) profile="${HOME}/.bash_profile" ;;
        zsh)  profile="${HOME}/.zshrc" ;;
        fish)
            local fish_conf="${HOME}/.config/fish/conf.d/navicode.fish"
            mkdir -p "$(dirname "${fish_conf}")"
            echo "set -gx PATH ${BIN_DIR} \$PATH" > "${fish_conf}"
            ok "PATH обновлён для fish"
            return 0
            ;;
        *)    profile="${HOME}/.profile" ;;
    esac

    if [[ -n "${profile}" ]]; then
        if ! grep -q "${BIN_DIR}" "${profile}" 2>/dev/null; then
            echo "" >> "${profile}"
            echo "# Navigator Code" >> "${profile}"
            echo "export PATH=\"${BIN_DIR}:\${PATH}\"" >> "${profile}"
            ok "PATH обновлён в ${profile}"
            warn "Выполните: source ${profile}  (или перезапустите терминал)"
        fi
    fi

    export PATH="${BIN_DIR}:${PATH}"
}

# ============================================
# Деинсталлятор
# ============================================
create_uninstaller() {
    cat > "${INSTALL_DIR}/uninstall.sh" <<'UNINSTALL'
#!/bin/bash
set -euo pipefail
APP_NAME="navigator"
INSTALL_DIR="${HOME}/.local/share/${APP_NAME}"
BIN_DIR="${HOME}/.local/bin"

echo ""
echo "Удаление Navigator Code..."
echo ""

rm -f "${BIN_DIR}/${APP_NAME}"
rm -f "${BIN_DIR}/${APP_NAME}-web"
echo "  ✓  Команды удалены"

rm -rf "${INSTALL_DIR}"
echo "  ✓  Каталог удалён: ${INSTALL_DIR}"

# Finder Quick Action
rm -rf "${HOME}/Library/Services/Открыть в Navigator Code.workflow" 2>/dev/null || true
/System/Library/CoreServices/pbs -update 2>/dev/null || true
echo "  ✓  Finder Quick Action удалён"

# Остатки MediaHit.Pro (если был установлен)
if [[ -d "${HOME}/.local/share/mediahit" || -e "${BIN_DIR}/mediahit" || -d "${HOME}/.mediahit" || -e "${HOME}/Library/Services/Открыть в MediaHit.workflow" ]]; then
    rm -rf "${HOME}/.local/share/mediahit" 2>/dev/null || true
    rm -f "${BIN_DIR}/mediahit" "${BIN_DIR}/mediahit-web" 2>/dev/null || true
    rm -rf "${HOME}/.mediahit" 2>/dev/null || true
    rm -rf "${HOME}/Library/Services/Открыть в MediaHit.workflow" 2>/dev/null || true
    for p in "${HOME}/.bash_profile" "${HOME}/.zshrc" "${HOME}/.profile"; do
        [[ -f "$p" ]] && sed -i.navbak '/# MediaHit\.Pro/,+1d' "$p" 2>/dev/null || true
    done
    echo "  ✓  Старый MediaHit.Pro также удалён"
fi

echo ""
echo "  ✓  Navigator Code удалён."
echo "  ℹ  Настройки сохранены в ~/.navicode/ (удалите вручную при необходимости)"
echo ""
UNINSTALL
    chmod +x "${INSTALL_DIR}/uninstall.sh"
}

# ============================================
# Основной процесс
# ============================================
# ============================================
# Установка Python и pip-пакетов (данные, документы, PDF)
# ============================================
setup_python() {
    local py_bin=""
    for cand in python3.12 python3.11 python3.10 python3.9 python3; do
        if command -v "${cand}" &>/dev/null; then
            local v
            v=$("${cand}" -c 'import sys;print("%d%02d"%sys.version_info[:2])' 2>/dev/null || echo 0)
            if [[ "${v}" -ge 309 ]]; then py_bin="${cand}"; break; fi
        fi
    done

    if [[ -z "${py_bin}" ]]; then
        warn "Python 3.9+ не найден."
        info "Установите: brew install python@3.11   (или скачайте python.org)"
        warn "Python-пакеты не установлены"
        return 0
    fi
    info "Python: ${py_bin} ($(${py_bin} --version 2>&1))"

    local venv_dir="${INSTALL_DIR}/python/.venv"
    mkdir -p "${INSTALL_DIR}/python"
    if [[ ! -d "${venv_dir}" ]]; then
        info "Создание venv в ${venv_dir}..."
        "${py_bin}" -m venv "${venv_dir}" || { warn "venv создать не удалось"; return 0; }
    fi
    local pip="${venv_dir}/bin/pip"
    "${pip}" install --quiet --upgrade pip 2>/dev/null || true

    # Архитектура: arm64 (Apple Silicon) или x86_64 (Intel)
    local arch
    arch=$(uname -m)
    local wheels_dir=""
    case "${arch}" in
        arm64)  wheels_dir="${SCRIPT_DIR}/python-wheels-macos-arm64" ;;
        x86_64) wheels_dir="${SCRIPT_DIR}/python-wheels-macos-x86_64" ;;
    esac

    local req="${SCRIPT_DIR}/requirements.txt"
    if [[ ! -f "${req}" ]]; then
        warn "requirements.txt не найден — пропускаю"
        return 0
    fi

    if [[ -n "${wheels_dir}" && -d "${wheels_dir}" ]]; then
        info "Установка пакетов из bundled wheels (${wheels_dir})..."
        "${pip}" install --no-index --find-links="${wheels_dir}" -r "${req}" \
            && ok "Python-пакеты установлены из оффлайн-wheels" \
            || warn "Часть пакетов не из wheels — добираю онлайн"
    fi

    info "Проверка/добор пакетов через PyPI..."
    "${pip}" install -r "${req}" \
        && ok "Python-пакеты готовы" \
        || warn "Не удалось установить часть пакетов (нет интернета?)"

    ln -sf "${venv_dir}/bin/python" "${BIN_DIR}/navigator-python" 2>/dev/null || true
    ln -sf "${venv_dir}/bin/pip" "${BIN_DIR}/navigator-pip" 2>/dev/null || true
    ok "Доступно: navigator-python, navigator-pip"
}

cleanup_previous_navigator() {
    local found=0
    [[ -d "${INSTALL_DIR}" ]] && found=1
    [[ -e "${BIN_DIR}/navicode" || -e "${BIN_DIR}/navigator" || -e "${BIN_DIR}/nav" ]] && found=1
    [[ -e "${BIN_DIR}/navigator-web" ]] && found=1
    [[ -d "${HOME}/Applications/Navigator Code.app" ]] && found=1
    [[ -d "${HOME}/Applications/Navigator Code Web.app" ]] && found=1

    if [[ ${found} -eq 0 ]]; then return 0; fi

    info "Обнаружена предыдущая установка Navigator Code — удаляю..."

    rm -f "${BIN_DIR}/navicode" "${BIN_DIR}/navigator" "${BIN_DIR}/nav" "${BIN_DIR}/navigator-web" 2>/dev/null || true
    rm -rf "${HOME}/Applications/Navigator Code.app" 2>/dev/null || true
    rm -rf "${HOME}/Applications/Navigator Code Web.app" 2>/dev/null || true
    rm -rf "${HOME}/Library/Services/Открыть в Navigator Code.workflow" 2>/dev/null || true
    rm -rf "${HOME}/Library/Services/Navigator Code Web.workflow" 2>/dev/null || true
    rm -rf "${INSTALL_DIR}" 2>/dev/null || true

    ok "Предыдущая установка удалена"
}

create_app_bundles() {
    local apps_dir="${HOME}/Applications"
    mkdir -p "${apps_dir}"

    # Путь к иконке (если есть)
    local icon_src="${INSTALL_DIR}/icon.png"

    # ── Navigator Code CLI .app ──
    local cli_app="${apps_dir}/Navigator Code.app"
    rm -rf "${cli_app}"
    mkdir -p "${cli_app}/Contents/MacOS"
    mkdir -p "${cli_app}/Contents/Resources"

    cat > "${cli_app}/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key><string>en</string>
    <key>CFBundleExecutable</key><string>navigator</string>
    <key>CFBundleIdentifier</key><string>com.navigator.code.cli</string>
    <key>CFBundleName</key><string>Navigator Code</string>
    <key>CFBundleShortVersionString</key><string>${APP_VERSION}</string>
    <key>CFBundleVersion</key><string>${APP_VERSION}</string>
    <key>CFBundleIconFile</key><string>icon</string>
    <key>CFBundlePackageType</key><string>APPL</string>
    <key>LSMinimumSystemVersion</key><string>10.15</string>
</dict>
</plist>
PLIST

    cat > "${cli_app}/Contents/MacOS/navigator" <<EXEC
#!/bin/bash
# Открываем Terminal.app с Navigator Code CLI
osascript -e '
tell application "Terminal"
    activate
    do script "${BIN_DIR}/navigator"
end tell
'
EXEC
    chmod +x "${cli_app}/Contents/MacOS/navigator"

    # Копируем иконку если есть
    if [[ -f "${icon_src}" ]]; then
        cp "${icon_src}" "${cli_app}/Contents/Resources/icon.png" 2>/dev/null || true
    fi
    ok "Ярлык: ${cli_app}"

    # ── Navigator Code Web .app ──
    local web_app="${apps_dir}/Navigator Code Web.app"
    rm -rf "${web_app}"
    mkdir -p "${web_app}/Contents/MacOS"
    mkdir -p "${web_app}/Contents/Resources"

    cat > "${web_app}/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key><string>en</string>
    <key>CFBundleExecutable</key><string>navigator-web</string>
    <key>CFBundleIdentifier</key><string>com.navigator.code.web</string>
    <key>CFBundleName</key><string>Navigator Code Web</string>
    <key>CFBundleShortVersionString</key><string>${APP_VERSION}</string>
    <key>CFBundleVersion</key><string>${APP_VERSION}</string>
    <key>CFBundleIconFile</key><string>icon</string>
    <key>CFBundlePackageType</key><string>APPL</string>
    <key>LSMinimumSystemVersion</key><string>10.15</string>
</dict>
</plist>
PLIST

    cat > "${web_app}/Contents/MacOS/navigator-web" <<EXEC
#!/bin/bash
exec "${BIN_DIR}/navigator-web" "\$@"
EXEC
    chmod +x "${web_app}/Contents/MacOS/navigator-web"

    if [[ -f "${icon_src}" ]]; then
        cp "${icon_src}" "${web_app}/Contents/Resources/icon.png" 2>/dev/null || true
    fi
    ok "Ярлык: ${web_app}"
}

main() {
    # Удаляем предыдущую установку Navigator Code
    cleanup_previous_navigator
    echo ""

    echo -e "${BOLD}[1/7] Node.js${NC}"
    if ! check_node; then
        install_node
    fi
    echo ""

    echo -e "${BOLD}[2/6] Приложение${NC}"
    install_app
    echo ""

    echo -e "${BOLD}[3/6] Команды${NC}"
    create_launcher
    echo ""

    echo -e "${BOLD}[4/6] PATH${NC}"
    ensure_path
    create_uninstaller
    echo ""

    echo -e "${BOLD}[5/7] Finder${NC}"
    create_finder_service
    echo ""

    echo -e "${BOLD}[6/7] Ярлыки .app${NC}"
    create_app_bundles
    echo ""

    echo -e "${BOLD}[7/7] Python и пакеты (данные, документы, PDF)${NC}"
    setup_python
    echo ""

    echo -e "${BOLD}============================================${NC}"
    echo -e "${GREEN}${BOLD}  Установка завершена!${NC}"
    echo -e "${BOLD}============================================${NC}"
    echo ""
    echo "  Запуск CLI:"
    echo "    ${APP_NAME}"
    echo ""
    echo "  Запуск Web GUI:"
    echo "    ${APP_NAME}-web"
    echo ""
    echo "  Удаление:"
    echo "    ${INSTALL_DIR}/uninstall.sh"
    echo ""

    if command -v "${APP_NAME}" &>/dev/null; then
        ok "Navigator Code готов к работе!"
    else
        warn "Перезапустите терминал или выполните:"
        echo "    export PATH=\"${BIN_DIR}:\${PATH}\""
    fi
    echo ""
}

main "$@"
