#!/usr/bin/env bash
# cortex-diary — per-agent diary through the Cortex API.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./_cortex_api.sh
source "${SCRIPT_DIR}/_cortex_api.sh"

usage() {
    cat <<'EOF'
Usage:
  cortex-diary <agent> [--last N]
  cortex-diary <agent> write --summary TEXT [--outcome completed|blocked|partial|handed-off] [--importance N]
  cortex-diary <agent> stats
EOF
}

if [ "$#" -lt 1 ] || [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
    usage
    exit 0
fi

AGENT_NAME="$(cortex_agent_base_name "$1" | tr '[:upper:]' '[:lower:]')"
shift
cmd="read"
if [ "$#" -gt 0 ]; then
    case "$1" in
        write|stats|read)
            cmd="$1"
            shift
            ;;
    esac
fi

render_json() {
    python3 -c 'import json,sys; data=json.load(sys.stdin); print(json.dumps(data, indent=2, sort_keys=True))'
}

case "${cmd}" in
    read)
        LAST_N=10
        while [ "$#" -gt 0 ]; do
            case "$1" in
                --last|--limit) LAST_N="$2"; shift 2 ;;
                --help|-h) usage; exit 0 ;;
                *) echo "ERROR: unknown option: $1" >&2; usage >&2; exit 2 ;;
            esac
        done
        cortex_api_call_json GET "/diary/${AGENT_NAME}?limit=${LAST_N}" "" "${AGENT_NAME}" | render_json
        ;;
    write)
        SUMMARY=""
        OUTCOME="completed"
        IMPORTANCE="5"
        while [ "$#" -gt 0 ]; do
            case "$1" in
                --summary) SUMMARY="$2"; shift 2 ;;
                --outcome) OUTCOME="$2"; shift 2 ;;
                --importance) IMPORTANCE="$2"; shift 2 ;;
                --help|-h) usage; exit 0 ;;
                *) echo "ERROR: unknown option: $1" >&2; usage >&2; exit 2 ;;
            esac
        done
        [ -n "${SUMMARY}" ] || { echo "ERROR: write requires --summary" >&2; exit 2; }
        payload="$(python3 - "${SUMMARY}" "${OUTCOME}" "${IMPORTANCE}" <<'PYEOF'
import json, sys
print(json.dumps({"summary": sys.argv[1], "outcome": sys.argv[2], "importance": int(sys.argv[3] or 5)}))
PYEOF
)"
        cortex_api_call_json POST "/diary/${AGENT_NAME}" "${payload}" "${AGENT_NAME}" | render_json
        ;;
    stats)
        cortex_api_call_json GET "/diary/${AGENT_NAME}/stats" "" "${AGENT_NAME}" | render_json
        ;;
esac
