#!/bin/bash
# ObserverFeed — watches git repo for changes and feeds diffs to an observer agent.
#
# Usage: ObserverFeed <session>/<agent> [interval]
#
# Watches the git working tree. When the diff changes, pushes the new diff
# to the agent's prompt. Runs until killed.
#
# Arguments:
#   session/agent   Target agent (e.g., myproj/observer)
#   interval        Poll interval in seconds (default: 5)
#
# The agent should be created first:
#   o myproj/observer new /path/to/repo
#
# Environment:
#   Respects the repo at the agent's cwd. Falls back to $PWD.

set -euo pipefail

if [[ $# -lt 1 ]]; then
    echo "usage: ObserverFeed <session>/<agent> [interval]" >&2
    exit 1
fi

TARGET="$1"
INTERVAL="${2:-5}"

# Parse session/agent
if [[ "$TARGET" != */* ]]; then
    echo "error: must specify session/agent (e.g., myproj/observer)" >&2
    exit 1
fi

SESSION="${TARGET%%/*}"
AGENT="${TARGET#*/}"
PROMPT_PATH="session/$SESSION/agent/$AGENT/prompt"

# Get the agent's cwd for the git repo
CWD=$(ollie-9p read "session/$SESSION/agent/$AGENT/cfg" 2>/dev/null | grep '^cwd=' | cut -d= -f2-)
if [[ -z "$CWD" ]]; then
    CWD="$PWD"
fi

cd "$CWD"

if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    echo "error: $CWD is not a git repository" >&2
    exit 1
fi

echo "[observer-feed] watching $CWD every ${INTERVAL}s → $TARGET"

LAST_DIFF=""

while true; do
    # Capture current diff (unstaged + staged vs HEAD)
    DIFF=$(git diff HEAD -- 2>/dev/null || true)

    if [[ -n "$DIFF" && "$DIFF" != "$LAST_DIFF" ]]; then
        printf '%s\n' "$DIFF" | ollie-9p write "$PROMPT_PATH"
        LAST_DIFF="$DIFF"
    fi

    sleep "$INTERVAL"
done
