#!/bin/bash

# txt2tex installer for macOS and Linux
# Usage: chmod +x install.sh && ./install.sh

# stop immediately if any command fails
set -e

# ── terminal colours ──────────────────────────────────────────
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

ok()   { echo -e "  ${GREEN}✓${NC}  $1"; }
info() { echo -e "  ${CYAN}→${NC}  $1"; }
warn() { echo -e "  ${YELLOW}!${NC}  $1"; }
fail() { echo -e "  ${RED}✗${NC}  $1"; exit 1; }
step() { echo -e "\n${BOLD}${CYAN}[$1/4] $2${NC}"; }

# ── banner ────────────────────────────────────────────────────
echo ""
echo -e "${CYAN}${BOLD}"
echo "  ████████╗██╗  ██╗████████╗██████╗ ████████╗███████╗██╗  ██╗"
echo "  ╚══██╔══╝╚██╗██╔╝╚══██╔══╝╚════██╗╚══██╔══╝██╔════╝╚██╗██╔╝"
echo "     ██║    ╚███╔╝    ██║    █████╔╝   ██║   █████╗   ╚███╔╝  "
echo "     ██║    ██╔██╗    ██║   ██╔═══╝    ██║   ██╔══╝   ██╔██╗  "
echo "     ██║   ██╔╝ ██╗   ██║   ███████╗   ██║   ███████╗██╔╝ ██╗ "
echo "     ╚═╝   ╚═╝  ╚═╝   ╚═╝   ╚══════╝   ╚═╝   ╚══════╝╚═╝  ╚═╝"
echo -e "${NC}"
echo -e "  ${BOLD}plain text  →  professional PDF resume${NC}"
echo ""
echo -e "  ${CYAN}version 0.1.0  •  github.com/deepiee/txt2tex${NC}"
echo ""
echo "  ─────────────────────────────────────────────────────"
echo ""
# ── Step 1: Rust ──────────────────────────────────────────────
step 1 "Checking Rust"

if command -v cargo &> /dev/null; then
    ok "Rust already installed: $(rustc --version)"
else
    info "Rust not found. Installing from rustup.rs..."
    if ! curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y; then
        fail "Rust installation failed. Install manually: https://rustup.rs"
    fi
    # load cargo into current shell session without restarting
    source "$HOME/.cargo/env"
    ok "Rust installed: $(rustc --version)"
fi

# ── Step 2: Neovim ────────────────────────────────────────────
step 2 "Checking Neovim"

if command -v nvim &> /dev/null; then
    ok "Neovim already installed: $(nvim --version | head -1)"
else
    info "Neovim not found. Installing..."
    OS="$(uname -s)"

    if [ "$OS" = "Darwin" ]; then
        if command -v brew &> /dev/null; then
            brew install neovim
            ok "Neovim installed via Homebrew"
        else
            warn "Homebrew not found. Install it from https://brew.sh then run: brew install neovim"
            warn "txt2tex will fall back to vim or nano for now."
        fi
    elif [ "$OS" = "Linux" ]; then
        if command -v apt-get &> /dev/null; then
            sudo apt-get update -qq
            sudo apt-get install -y neovim
            ok "Neovim installed via apt"
        elif command -v dnf &> /dev/null; then
            sudo dnf install -y neovim
            ok "Neovim installed via dnf"
        elif command -v pacman &> /dev/null; then
            sudo pacman -S --noconfirm neovim
            ok "Neovim installed via pacman"
        else
            warn "Unknown package manager. Install neovim manually: https://neovim.io"
        fi
    fi
fi

# set EDITOR=nvim in shell config if nvim is available
if command -v nvim &> /dev/null; then
    # figure out which shell config file to use
    SHELL_RC=""
    if [ -f "$HOME/.zshrc" ];  then SHELL_RC="$HOME/.zshrc";
    elif [ -f "$HOME/.bashrc" ]; then SHELL_RC="$HOME/.bashrc"; fi

    if [ -n "$SHELL_RC" ]; then
        if ! grep -q 'EDITOR=nvim' "$SHELL_RC"; then
            echo '' >> "$SHELL_RC"
            echo '# set by txt2tex installer' >> "$SHELL_RC"
            echo 'export EDITOR=nvim' >> "$SHELL_RC"
            ok "Added EDITOR=nvim to $SHELL_RC"
        else
            ok "EDITOR=nvim already in $SHELL_RC"
        fi
    fi
    export EDITOR=nvim
fi

# ── Step 3: Tectonic ──────────────────────────────────────────
step 3 "Checking Tectonic (LaTeX engine)"

if command -v tectonic &> /dev/null; then
    ok "Tectonic already installed: $(tectonic --version)"
else
    info "Tectonic not found. Installing..."
    OS="$(uname -s)"
    ARCH="$(uname -m)"

    if [ "$OS" = "Darwin" ]; then
        # macOS: homebrew is fastest
        if command -v brew &> /dev/null; then
            brew install tectonic
            ok "Tectonic installed via Homebrew"
        else
            warn "No Homebrew. Installing tectonic via cargo (this takes ~5 minutes)..."
            cargo install tectonic
            ok "Tectonic installed via cargo"
        fi

    elif [ "$OS" = "Linux" ]; then
        # Linux: try pre-built binary first (much faster than cargo install)
        TECTONIC_VERSION="0.15.0"

        if [ "$ARCH" = "x86_64" ]; then
            BIN_URL="https://github.com/tectonic-typesetting/tectonic/releases/download/tectonic%40${TECTONIC_VERSION}/tectonic-${TECTONIC_VERSION}-x86_64-unknown-linux-musl.tar.gz"
        elif [ "$ARCH" = "aarch64" ]; then
            BIN_URL="https://github.com/tectonic-typesetting/tectonic/releases/download/tectonic%40${TECTONIC_VERSION}/tectonic-${TECTONIC_VERSION}-aarch64-unknown-linux-musl.tar.gz"
        else
            BIN_URL=""
        fi

        if [ -n "$BIN_URL" ]; then
            INSTALL_DIR="$HOME/.local/bin"
            mkdir -p "$INSTALL_DIR"

            if curl -L "$BIN_URL" | tar -xz -C "$INSTALL_DIR" tectonic 2>/dev/null; then
                chmod +x "$INSTALL_DIR/tectonic"
                # add to PATH if not already there
                if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
                    export PATH="$INSTALL_DIR:$PATH"
                    echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$HOME/.bashrc"
                    echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$HOME/.zshrc" 2>/dev/null || true
                fi
                ok "Tectonic installed to $INSTALL_DIR"
            else
                warn "Binary download failed. Falling back to cargo install..."
                install_tectonic_cargo
            fi
        else
            install_tectonic_cargo
        fi
    fi
fi

# installs tectonic via cargo (Linux fallback)
# needs system libraries first
install_tectonic_cargo() {
    info "Installing system dependencies for tectonic..."
    if command -v apt-get &> /dev/null; then
        sudo apt-get install -y libssl-dev pkg-config libfreetype6-dev \
            libfontconfig1-dev libgraphite2-dev libharfbuzz-dev \
            libicu-dev zlib1g-dev 2>/dev/null
    elif command -v dnf &> /dev/null; then
        sudo dnf install -y openssl-devel freetype-devel fontconfig-devel \
            graphite2-devel harfbuzz-devel libicu-devel zlib-devel 2>/dev/null
    elif command -v pacman &> /dev/null; then
        sudo pacman -S --noconfirm openssl freetype2 fontconfig \
            graphite harfbuzz icu zlib 2>/dev/null
    fi
    cargo install tectonic
    ok "Tectonic installed via cargo"
}

# ── Step 4: txt2tex ───────────────────────────────────────────
step 4 "Installing txt2tex"

info "Compiling and installing (this takes about 30 seconds)..."
cargo install --path .
ok "txt2tex installed to $(which txt2tex)"

# ── Done ──────────────────────────────────────────────────────
echo ""
echo "  ─────────────────────────────────────────────────────"
echo ""
echo -e "  ${GREEN}${BOLD}Installation complete!${NC}"
echo ""
echo "  Commands:"
echo ""
echo -e "  ${CYAN}txt2tex${NC}           create/edit resume in current folder, generate PDF"
echo -e "  ${CYAN}txt2tex new${NC}       create fresh resume.txt from template"
echo -e "  ${CYAN}txt2tex analyze${NC}   check resume for weak spots"
echo -e "  ${CYAN}txt2tex --no-edit${NC} skip editor, regenerate PDF"
echo -e "  ${CYAN}txt2tex --dry-run${NC} parse and print data, no PDF"
echo -e "  ${CYAN}txt2tex --help${NC}    show all options"
echo ""
echo -e "  ${YELLOW}Restart your terminal for EDITOR=nvim to take effect.${NC}"
echo ""
