#!/bin/bash
# acme-ollie-ensure - Ensure acme session and agent exist
#
# One session per project root (git worktree aware), one agent "assistant".
# Session name: acme-{hash of project root}
#
# Usage: eval $(acme-ollie-ensure)
#        Then use $OLLIE_SESSION and $OLLIE_AGENT

set -euo pipefail

# Acme sets $PWD to the window's directory for executed commands.
# Fall back to tag parsing if $winid is set (e.g. for pipe commands).
cwd="$PWD"
if [[ -n "${winid:-}" ]] && [[ "$cwd" == "$HOME" || "$cwd" == "$HOME/" ]]; then
    # PWD is $HOME — likely the top-level window. Try tag-based detection.
    wname=$(9p read "acme/$winid/tag" | awk '{print $1}')
    if [[ -d "$wname" ]]; then
        cwd="$wname"
    elif [[ -f "$wname" ]]; then
        cwd=$(dirname "$wname")
    fi
fi

# Discover project root: git worktree root > cwd
project_root="$cwd"
if wt_root=$(git -C "$cwd" rev-parse --show-toplevel 2>/dev/null); then
    project_root="$wt_root"
fi

# Session name from project root hash
session_hash=$(printf '%s' "$project_root" | md5sum | cut -c1-8)
SESSION="acme-$session_hash"
AGENT="assistant"

# Ensure session exists (with project root as cwd)
if ! ollie-9p read "session/$SESSION/env" >/dev/null 2>&1; then
    printf 'name=%s\ncwd=%s\n' "$SESSION" "$project_root" | ollie-9p write "session/new" 2>/dev/null || true
fi

# Ensure agent exists
if ! ollie-9p read "session/$SESSION/agent/$AGENT/cfg" >/dev/null 2>&1; then
    printf 'name=%s\n' "$AGENT" | ollie-9p write "session/$SESSION/agent/new" 2>/dev/null || true
fi

# Output for eval
echo "export OLLIE_SESSION=$SESSION"
echo "export OLLIE_AGENT=$AGENT"
