#!/bin/bash
# Explain - Ask ollie to explain the selected code in acme
#
# Usage: Select code, then middle-click Explain in the tag

set -euo pipefail

if [[ -z "${winid:-}" ]]; then
    echo "Explain must be run from within acme" >&2
    exit 1
fi

# Get the window name (filename) from the tag
filename=$(9p read acme/$winid/tag | awk '{print $1}')

# Read the current selection
echo 'addr=dot' | 9p write acme/$winid/ctl
selection=$(9p read acme/$winid/xdata 2>/dev/null || true)

if [[ -z "$selection" ]]; then
    echo "No selection. Select some code first." >&2
    exit 1
fi

# Ensure acme session/agent exists
eval $(acme-ollie-ensure)

# Build context string
context=""
if [[ -n "$filename" && "$filename" != *"+Errors" && "$filename" != "+*" ]]; then
    context=" (from $filename)"
fi

# Build and send the prompt
prompt="Read-only task. Inspect the actual file $filename and explain the selected code below. Do not edit files. Explain what it does, how it works, important inputs and outputs, and any risks or edge cases. The selection is the target, not necessarily the complete context.

File: $filename
Selected code:

a code selection follows:
$selection

Give a concise explanation. Do not propose or apply a patch."

echo "$prompt" | o "$OLLIE_SESSION/$OLLIE_AGENT" prompt
