#!/bin/bash
# acme-ollie-ensure - Ensure acme session and agent exist
#
# Creates session "acme" if needed, creates/selects agent based on cwd hash.
# 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

# Create a short hash from the cwd for the agent name
# Use first 8 chars of md5sum for uniqueness
agent_hash=$(echo -n "$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"
