#!/bin/sh
# ollie-session-here: start a session in the given directory
# Works from both Dolphin (passes %f) and terminal (uses $PWD).
#
# Session is always "default". Agent name follows convention: prefix:basename
# where prefix is parent dir split at first _ (e.g., src:ollie, md-20470:mobydick)
# Session/agent creation is idempotent.

TARGET="$1"
[ -f "$TARGET" ] && TARGET="$(dirname "$TARGET")"
[ -z "$TARGET" ] && TARGET="$PWD"
TARGET="$(cd "$TARGET" 2>/dev/null && pwd)" || TARGET="$PWD"

# Compute agent name: prefix:basename
# prefix = parent dirname, split at first _ if present
PARENT="$(basename "$(dirname "$TARGET")")"
BASENAME="$(basename "$TARGET")"
case "$PARENT" in
    *_*) PREFIX="${PARENT%%_*}" ;;
    *)   PREFIX="$PARENT" ;;
esac
# Slugify: lowercase, replace non-alnum with -
AGENT_NAME="$(printf '%s:%s' "$PREFIX" "$BASENAME" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9:-]/-/g')"

# Create default session (idempotent)
printf 'name=default\ncwd=%s\n' "$TARGET" | ollie-9p rdwr session/new >/dev/null 2>&1

# Create or update agent with computed name
if ollie-9p read "session/default/agent/$AGENT_NAME/cfg" >/dev/null 2>&1; then
    # Agent exists, update cwd
    printf 'cwd %s' "$TARGET" | ollie-9p rdwr "session/default/agent/$AGENT_NAME/ctl" >/dev/null 2>&1
else
    # Create new agent
    printf 'name=%s\ncwd=%s\n' "$AGENT_NAME" "$TARGET" | ollie-9p rdwr session/default/agent/new >/dev/null 2>&1
fi

if [ -t 1 ]; then
    # Terminal: print session info
    echo "Session: default"
    echo "Agent: $AGENT_NAME"
    echo "CWD: $TARGET"
else
    # Dolphin/non-interactive: desktop notification
    notify-send -t 3000 "Ollie" "Agent '$AGENT_NAME' started in $TARGET"
fi
