#!/bin/bash
set -euo pipefail

GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

ZOOM_PATCH_STATUS="přeskočen"
DOOM_STATUS="neznámý"
# Zachyť cestu ke skriptu PŘED jakýmkoli cd
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# --- Předběžné kontroly ---
if [[ "$(uname -s)" != "Darwin" ]]; then
    echo "Tento skript je pro macOS." && exit 1
fi

if ! command -v brew &>/dev/null; then
    echo "Homebrew nenalezen. Nainstaluj: https://brew.sh" && exit 1
fi

# --- [1/7] Prerekvizity ---
echo -e "${GREEN}[1/7] Prerekvizity...${NC}"
PACKAGES=(autoconf gmp texinfo pkg-config gnutls libxml2 jansson tree-sitter librsvg imagemagick)
for pkg in "${PACKAGES[@]}"; do
    if ! brew list "$pkg" &>/dev/null; then
        echo "  Instaluji $pkg..."
        brew install "$pkg"
    else
        echo "  $pkg již nainstalován"
    fi
done
TREE_SITTER_VERSION=$(brew list tree-sitter --versions 2>/dev/null | awk '{print $2}' || echo "unknown")
echo "  tree-sitter verze: $TREE_SITTER_VERSION"

# --- [2/7] Emacs zdroj ---
echo -e "${GREEN}[2/7] Emacs zdroj...${NC}"
if [[ ! -d ~/src/emacs/.git ]]; then
    git clone --depth 50 https://github.com/emacs-mirror/emacs.git ~/src/emacs
    cd ~/src/emacs
else
    cd ~/src/emacs
    git pull --rebase
fi

# --- [3/7] Zoom accessibility patch ---
echo -e "${GREEN}[3/7] Zoom accessibility patch...${NC}"
PATCH_NAME="0001-ns-implement-AXBoundsForRange-for-macOS-Zoom-cursor-.patch"
PATCH_FILE=""
for _dir in "${SCRIPT_DIR}/../patches" "${HOME}/.doom.d/patches" "${HOME}/.config/doom/patches"; do
    if [[ -f "${_dir}/${PATCH_NAME}" ]]; then
        PATCH_FILE="${_dir}/${PATCH_NAME}"
        break
    fi
done
cd ~/src/emacs
if grep -q UAZoomChangeFocus src/nsterm.m 2>/dev/null; then
    echo "  Patch already applied, skipping"
    ZOOM_PATCH_STATUS="aplikován (již dříve)"
elif [[ -z "$PATCH_FILE" ]]; then
    echo -e "${RED}  Patch soubor nenalezen v ~/.doom.d/patches/, ~/.config/doom/patches/ ani vedle skriptu${NC}"
    ZOOM_PATCH_STATUS="přeskočen (soubor chybí)"
else
    if git am --ignore-whitespace "$PATCH_FILE"; then
        echo "  Patch aplikován"
        ZOOM_PATCH_STATUS="aplikován"
    else
        git am --abort 2>/dev/null || true
        echo -e "${RED}  WARNING: Patch selhal (conflict). Pokračuji bez patche.${NC}"
        ZOOM_PATCH_STATUS="selhal"
    fi
fi

# --- [4/7] Build ---
echo -e "${GREEN}[4/7] Build...${NC}"
cd ~/src/emacs
./autogen.sh
./configure \
    --with-ns \
    --with-tree-sitter \
    --with-gnutls \
    --with-xml2 \
    --with-json \
    --with-imagemagick \
    --with-rsvg \
    --without-x \
    --without-dbus \
    CFLAGS="-O2 -g3"

set +o pipefail
make -j"$(sysctl -n hw.ncpu)" 2>&1 | tee /tmp/emacs-build.log
MAKE_EXIT=${PIPESTATUS[0]}
set -o pipefail

if [[ "$MAKE_EXIT" -ne 0 ]]; then
    echo -e "${RED}BUILD FAILED, see /tmp/emacs-build.log${NC}"
    exit 1
fi

# make install (--with-ns) zkompletuje nextstep/Emacs.app — kopíruje lisp/ a libexec/
make install 2>&1 | tee -a /tmp/emacs-build.log

# --- [5/7] Install do /Applications ---
echo -e "${GREEN}[5/7] Install do /Applications...${NC}"
sudo rm -rf /Applications/Emacs.app
cp -r nextstep/Emacs.app /Applications/
codesign --force --deep --sign - /Applications/Emacs.app
echo "  Emacs.app nainstalován a podepsán"

# --- [6/7] Wrapper v /usr/local/bin/emacs ---
echo -e "${GREEN}[6/7] Wrapper v /usr/local/bin/emacs...${NC}"
sudo tee /usr/local/bin/emacs > /dev/null << 'EOF'
#!/bin/bash
exec /Applications/Emacs.app/Contents/MacOS/Emacs "$@"
EOF
sudo chmod +x /usr/local/bin/emacs
echo "  Wrapper vytvořen"

# --- [7/7] Doom Emacs ---
echo -e "${GREEN}[7/7] Doom Emacs...${NC}"
if [[ -d ~/.config/emacs/.git ]]; then
    echo "  Doom existuje, upgraduji..."
    ~/.config/emacs/bin/doom upgrade --force
    DOOM_STATUS="upgradován"
else
    echo "  Doom neexistuje, instaluji..."
    git clone --depth 1 https://github.com/doomemacs/doomemacs ~/.config/emacs
    ~/.config/emacs/bin/doom install --no-fonts --no-env
    DOOM_STATUS="nainstalován"
fi

# --- Závěrečné info ---
echo ""
echo "=== Emacs install hotov ==="
echo "Verze: $(/usr/local/bin/emacs --version 2>/dev/null | head -1 || echo "N/A")"
echo "tree-sitter: $TREE_SITTER_VERSION"
echo "Zoom patch: $ZOOM_PATCH_STATUS"
echo "Doom: $DOOM_STATUS"
echo ""
echo "Spusť: emacs"
echo "Nebo: open /Applications/Emacs.app"

brew install pipx
brew install pyright
pipx install isort pytest
brew install coreutils
brew install ruff
