#!/bin/bash
# acme-ollie-ensure - Ensure acme session and agent exist
#
# Creates session "acme" if needed, creates/selects one agent per git root.
# Outputs the session and agent names for use by other scripts.
#
# Usage: eval $(acme-ollie-ensure)
#        Then use $OLLIE_SESSION and $OLLIE_AGENT

set -euo pipefail

SESSION="acme"

# Get cwd from the acme window's directory context
if [[ -n "${winid:-}" ]]; then
    # Get window name and extract directory
    wname=$(9p read acme/$winid/tag | awk '{print $1}')
    if [[ -d "$wname" ]]; then
        cwd="$wname"
    elif [[ -f "$wname" ]]; then
        cwd=$(dirname "$wname")
    else
        cwd="$HOME"
    fi
else
    cwd="$PWD"
fi

# Walk up to the repository root so all files in one checkout share an agent.
git_root=$(git -C "$cwd" rev-parse --show-toplevel 2>/dev/null || true)
if [[ -n "$git_root" ]]; then
    cwd="$git_root"
fi

# Create a short hash from the project root for the agent name
agent_hash=$(printf '%s' "$cwd" | md5sum | cut -c1-8)
AGENT="$agent_hash"

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

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

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