#!/bin/bash
# AddTests - Ask ollie to write unit tests for the selected code
#
# Usage: Select code, then middle-click AddTests in the tag

set -euo pipefail

if [[ -z "${winid:-}" ]]; then
    echo "AddTests 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 location string
location=""
if [[ -n "$filename" && "$filename" != *"+Errors" && "$filename" != "+*" ]]; then
    location=" in \`$filename\`"
fi

# Build and send the prompt
prompt="Edit the source tree to add tests for the selected code in $filename.

The selected code below is the target. It may be incomplete context:

$selection

Instructions:
- Read the actual source file, existing tests, and project test conventions first.
- Add focused unit tests for normal behavior, important edge cases, and errors.
- Do not change production code unless a test requires a minimal testability fix.
- Do not rewrite or remove existing tests.
- Apply the tests directly to the repository. Do not only describe test code.
- Format the files and run the relevant tests.

After editing, report the test files changed and the test command and result."

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