#!/usr/bin/env bash
#
# fido — launcher for the Fido coding assistant.
#
# Installed to $FIDO_HOME/bin/fido (default ~/.fido/bin/fido) by install.sh, but
# this file also works when run straight from a source checkout (bin/fido ->
# ../src/fido.js).
#
# All per-user state is kept under $FIDO_HOME:
#   $FIDO_HOME/.env                            your API keys / model config
#   $FIDO_HOME/state/<workspace>/undo.json     the undo log for that workspace
#   $FIDO_HOME/state/<workspace>/suspends/     /suspend snapshots for it
#
# Every workspace you run fido in gets its own state folder, so undo/suspend
# history never mixes between projects — and never litters the projects
# themselves (no more .fido-undo.json / .fido-suspends in your repos).

set -euo pipefail

FIDO_HOME="${FIDO_HOME:-$HOME/.fido}"

# ── Load user config ──────────────────────────────────────────────────────────
# Exported vars win over any .env inside the workspace, because dotenv (used by
# src/config.js) never overwrites variables already present in the environment.
if [ -f "$FIDO_HOME/.env" ]; then
    set -a
    # shellcheck disable=SC1090
    . "$FIDO_HOME/.env"
    set +a
fi

# ── Resolve the app directory ─────────────────────────────────────────────────
if [ -f "$FIDO_HOME/app/src/fido.js" ]; then
    APP_DIR="$FIDO_HOME/app"
else
    # Running from a source checkout: this script lives in <root>/bin/.
    self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    APP_DIR="$(cd "$self_dir/.." && pwd)"
fi

# ── Per-workspace state under $FIDO_HOME/state/<slug>/ ────────────────────────
# The workspace is the first argument (like the app itself: `fido /path/to/proj`),
# falling back to the current directory.
workspace="${1:-$PWD}"
if [ -d "$workspace" ]; then
    workspace="$(cd "$workspace" && pwd)"
else
    workspace="$PWD"
fi

# Human-readable, filesystem-safe slug + a short hash to guarantee uniqueness.
slug="$(printf '%s' "$workspace" | sed -e 's,^/,,' -e 's,/,_,g' -e 's,[^A-Za-z0-9._-],-,g')"
[ -n "$slug" ] || slug="root"
sum="$(printf '%s' "$workspace" | cksum | cut -d' ' -f1)"
state_dir="$FIDO_HOME/state/${slug}-${sum}"
mkdir -p "$state_dir/suspends"

export UNDO_FILE="$state_dir/undo.json"
export SUSPEND_DIR="$state_dir/suspends"

exec node "$APP_DIR/src/fido.js" "$@"
