#!/bin/bash
# acme-ollie-ensure - Ensure acme session and agent exist
#
# One session "acme", one agent per project directory.
# Agent name: prefix:basename (e.g., src:ollie, md-20470:mobydick)
# If parent dir contains _, use prefix before first _ (e.g., MD-20470_feature -> md-20470)
#
# Usage: eval $(acme-ollie-ensure)
#        Then use $OLLIE_SESSION and $OLLIE_AGENT

set -euo pipefail

# Compute agent name from directory path
# Format: prefix:basename (parent split at first _ if present)
agent_name_from_cwd() {
    local cwd="$1"
    local parent basename prefix
    parent=$(basename "$(dirname "$cwd")")
    basename=$(basename "$cwd")
    # Split parent at first underscore if present
    if [[ "$parent" == *_* ]]; then
        prefix="${parent%%_*}"
    else
        prefix="$parent"
    fi
    # Slugify: lowercase, replace non-alnum with -
    echo "${prefix}:${basename}" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9:-]/-/g'
}

# 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="acme"
AGENT=$(agent_name_from_cwd "$project_root")

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

# Ensure agent exists and has correct cwd
if ollie-9p read "session/$SESSION/agent/$AGENT/cfg" >/dev/null 2>&1; then
    # Agent exists, update cwd
    printf 'cwd %s' "$project_root" | ollie-9p rdwr "session/$SESSION/agent/$AGENT/ctl" >/dev/null 2>&1 || true
else
    # Create new agent with cwd
    printf 'name=%s\ncwd=%s\n' "$AGENT" "$project_root" | ollie-9p rdwr "session/$SESSION/agent/new" >/dev/null 2>&1 || true
fi

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