#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
INPUT=${1:-}
OUTPUT=${2:-}

if [ -z "$INPUT" ] || [ -z "$OUTPUT" ]; then
  echo "Usage: $0 proposals.json recommendations.json" >&2
  exit 1
fi

if [ ! -f "$INPUT" ]; then
  echo "Input file does not exist: $INPUT" >&2
  exit 1
fi

if ! command -v codex >/dev/null 2>&1; then
  echo "Local Codex CLI is not installed." >&2
  exit 1
fi

LOGIN_STATUS=$(codex login status 2>&1)
if [ "$LOGIN_STATUS" != "Logged in using ChatGPT" ]; then
  echo "Codex must be logged in through the user's ChatGPT subscription." >&2
  echo "Observed status: $LOGIN_STATUS" >&2
  exit 1
fi

{
  echo "Review the following community proposals for mutual-aid categories."
  echo "Return advisory recommendations only; never claim that a database action happened."
  echo "Prioritize safe, legal, non-commercial mutual aid. Flag ambiguous or risky proposals for manual_review."
  echo "Prefer merging duplicates into an existing parent when the input supports that conclusion."
  echo "Input JSON follows:"
  sed -n '1,$p' "$INPUT"
} | codex exec \
  --ephemeral \
  --sandbox read-only \
  --output-schema "$ROOT/docs/category-moderation-output.schema.json" \
  --output-last-message "$OUTPUT" \
  -

echo "Advisory recommendations written to $OUTPUT"
