#!/usr/bin/env bash
# dev-session.sh — build ltk + crustace + forge, neutralise the host
# compositor's Alt+Tab so forge's switcher gets the keys, launch a few
# test apps inside the nested forge, and stream forge's log until Ctrl+C.
# Restores the original Alt+Tab keybindings on exit.
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
FORGE_BIN="$HERE/forge/target/debug/forge"
CRUSTACE_BIN="$HERE/crustace/target/debug/crustace"
LTK_THEMES_DIR="$HERE/ltk/themes"

# ── build (ltk first so ltk-only errors show up cleanly) ──────────────────────
echo "==> Building ltk..."
cargo build --manifest-path "$HERE/ltk/Cargo.toml" 2>&1 \
    | grep -E "^error|^Compiling|^Finished|^error\[" || true

echo "==> Building crustace..."
cargo build --manifest-path "$HERE/crustace/Cargo.toml" 2>&1 \
    | grep -E "^error|^Compiling|^Finished|^error\[" || true

echo "==> Building forge (winit)..."
cargo build --features winit --manifest-path "$HERE/forge/Cargo.toml" 2>&1 \
    | grep -E "^error|^Compiling|^Finished|^error\[" || true

[ -x "$FORGE_BIN" ]    || { echo "ERROR: forge binary missing — build failed"    >&2; exit 1; }
[ -x "$CRUSTACE_BIN" ] || { echo "ERROR: crustace binary missing — build failed" >&2; exit 1; }
echo "==> Build OK"

# ── neutralise host GNOME's Alt+Tab so forge sees the keys ────────────────────
# These bindings would otherwise be intercepted by the outer mutter and
# never reach forge's input handler in nested mode. Saved values are
# restored from the cleanup trap below.
declare -A SAVED_KEYS=()
GS_KEYS=(switch-applications switch-applications-backward
         switch-windows       switch-windows-backward
         switch-group         switch-group-backward)
if command -v gsettings >/dev/null 2>&1; then
    for k in "${GS_KEYS[@]}"; do
        SAVED_KEYS[$k]=$(gsettings get org.gnome.desktop.wm.keybindings "$k" 2>/dev/null || echo "@as []")
        gsettings set org.gnome.desktop.wm.keybindings "$k" "[]" 2>/dev/null || true
    done
    echo "==> GNOME Alt+Tab bindings disabled (will be restored on exit)"
fi

# ── launch forge ──────────────────────────────────────────────────────────────
FORGE_LOG=$(mktemp /tmp/forge-XXXXXX.log)
FORGE_PID=""

cleanup() {
    echo ""
    echo "[dev] shutting down..."
    [ -n "$FORGE_PID" ] && kill "$FORGE_PID" 2>/dev/null || true
    wait 2>/dev/null || true
    if command -v gsettings >/dev/null 2>&1; then
        for k in "${GS_KEYS[@]}"; do
            [ -n "${SAVED_KEYS[$k]:-}" ] && \
                gsettings set org.gnome.desktop.wm.keybindings "$k" "${SAVED_KEYS[$k]}" 2>/dev/null || true
        done
        echo "[dev] GNOME keybindings restored"
    fi
}
trap cleanup EXIT INT TERM

RUST_LOG="forge=info,forge::corner_action=debug,smithay=warn" \
RUST_BACKTRACE=1 \
LTK_THEMES_DIR="$LTK_THEMES_DIR" \
"$FORGE_BIN" --winit --size 480x900 --exec "$CRUSTACE_BIN" >"$FORGE_LOG" 2>&1 &
FORGE_PID=$!

# ── wait for socket ───────────────────────────────────────────────────────────
echo -n "==> Waiting for forge socket"
FORGE_DISPLAY=""
for _ in $(seq 1 60); do
    if ! kill -0 "$FORGE_PID" 2>/dev/null; then
        echo ""
        echo "ERROR: forge exited. Log:" >&2
        cat "$FORGE_LOG" >&2
        exit 1
    fi
    FORGE_DISPLAY=$(grep -m1 "Wayland socket:" "$FORGE_LOG" 2>/dev/null \
                    | grep -oP 'wayland-\d+' || true)
    [ -n "$FORGE_DISPLAY" ] && break
    echo -n "."
    sleep 0.25
done
echo ""

if [ -z "$FORGE_DISPLAY" ]; then
    echo "ERROR: forge socket not found. Log:" >&2
    cat "$FORGE_LOG" >&2
    exit 1
fi

echo "==> forge on $FORGE_DISPLAY (pid: $FORGE_PID, log: $FORGE_LOG)"
sleep 1.5  # let crustace's shell come up

# ── launch a handful of test apps inside forge ────────────────────────────────
echo "==> Opening test apps inside forge..."
WAYLAND_DISPLAY="$FORGE_DISPLAY" gnome-calculator   >/dev/null 2>&1 &
WAYLAND_DISPLAY="$FORGE_DISPLAY" gnome-calendar     >/dev/null 2>&1 &
WAYLAND_DISPLAY="$FORGE_DISPLAY" gnome-text-editor  >/dev/null 2>&1 &

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  forge display : $FORGE_DISPLAY"
echo "  Alt+Tab       : keyboard switcher (host bindings disabled)"
echo "  Super+Tab     : alias for Alt+Tab"
echo "  Corner TL     : open switcher via mouse"
echo "  Ctrl+C        : stop everything (restores host keybindings)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# ── live logs ─────────────────────────────────────────────────────────────────
tail -f "$FORGE_LOG" | sed -E --unbuffered 's/^/\x1b[34m[forge]   \x1b[0m/' &

wait "$FORGE_PID" 2>/dev/null || true
