#!/bin/bash
# kel — post a message to the team Kel space via the shared incoming webhook.
#
# Reads the webhook URL from ~/.config/gchat-webhooks.json → spaces.kel.url.
# The URL is distributed to all Adom team employee containers by
# `gallia/install.mjs` (private-repo gate = team membership gate).
#
# EVERY message is attributed: "*Kel (on behalf of <user>)*  <body>".
# Identity is read from ~/.config/adom-identity.json (populated by install.mjs).
#
# ⚠ SECURITY: this script NEVER reveals the container slug or the Docker short
# hostname. Those values are effectively passwords — exposing them lets anyone
# construct internal container URLs (coder.*.containers.adom.inc) and reach
# internal services. Only the Adom `user` name and `repo` name are safe to share.
# See the `adom-security` wiki skill for the full rule set.
#
# Usage:
#   kel "message text"
#   kel --thread my-deploy "message text"  # post into a threaded reply
#   echo "streamed" | kel --stdin          # post from stdin
#   kel --with-repo "message"              # append "via <repo>" to attribution
#   kel --no-attribution "message"         # skip "on behalf of" prefix (rare)
#
# Google Chat formatting supported: *bold*, _italic_, ~strike~, `code`, ```fenced```.

set -u

WEBHOOK_CFG="$HOME/.config/gchat-webhooks.json"
IDENTITY_CFG="$HOME/.config/adom-identity.json"
SPACE="kel"
THREAD=""
USE_STDIN=0
WITH_REPO=0
ATTRIBUTE=1

usage() {
  sed -n '2,23p' "$0"
  exit 2
}

while [ $# -gt 0 ]; do
  case "$1" in
    --space)           SPACE="$2"; shift 2 ;;
    --thread)          THREAD="$2"; shift 2 ;;
    --stdin)           USE_STDIN=1; shift ;;
    --with-repo)       WITH_REPO=1; shift ;;
    --no-attribution)  ATTRIBUTE=0; shift ;;
    -h|--help)         usage ;;
    --)                shift; break ;;
    -*)                echo "unknown flag: $1" >&2; usage ;;
    *)                 break ;;
  esac
done

if [ "$USE_STDIN" = "1" ]; then
  TEXT="$(cat)"
else
  TEXT="${*:-}"
fi

if [ -z "$TEXT" ]; then
  echo "kel: empty message" >&2
  exit 2
fi

if [ ! -f "$WEBHOOK_CFG" ]; then
  echo "kel: no config at $WEBHOOK_CFG — run \`node ~/project/gallia/install.mjs\`" >&2
  exit 1
fi

URL=$(python3 -c "
import json
try:
    d = json.load(open('$WEBHOOK_CFG'))
    print(d.get('spaces', {}).get('$SPACE', {}).get('url', ''))
except Exception:
    pass
" 2>/dev/null)

if [ -z "$URL" ]; then
  echo "kel: space '$SPACE' has no webhook URL in $WEBHOOK_CFG" >&2
  exit 1
fi

# Build attribution prefix. SAFE fields only: user name + optional repo name.
# NEVER use $(hostname), slug, or any container ID.
if [ "$ATTRIBUTE" = "1" ]; then
  USER_NAME=""
  REPO_NAME=""
  if [ -f "$IDENTITY_CFG" ]; then
    USER_NAME=$(python3 -c "import json; d=json.load(open('$IDENTITY_CFG')); print(d.get('user',''))" 2>/dev/null)
    REPO_NAME=$(python3 -c "import json; d=json.load(open('$IDENTITY_CFG')); print(d.get('repo',''))" 2>/dev/null)
  fi
  if [ -z "$USER_NAME" ]; then
    # Fallback: query adom-cli (slower, but avoids leaking)
    USER_NAME=$(adom-cli carbon user get 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('name',''))" 2>/dev/null)
  fi
  if [ -z "$USER_NAME" ]; then
    USER_NAME="unknown"
  fi
  PREFIX="*Kel (on behalf of ${USER_NAME})*"
  if [ "$WITH_REPO" = "1" ] && [ -n "$REPO_NAME" ]; then
    PREFIX="*Kel (on behalf of ${USER_NAME} via ${REPO_NAME})*"
  fi
  TEXT="${PREFIX}  ${TEXT}"
fi

if [ -n "$THREAD" ]; then
  sep="?"
  case "$URL" in *"?"*) sep="&" ;; esac
  URL="${URL}${sep}threadKey=${THREAD}&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
fi

payload=$(python3 -c "import json,sys; print(json.dumps({'text': sys.stdin.read()}))" <<< "$TEXT")

response=$(curl -sS --max-time 10 -X POST \
  -H 'Content-Type: application/json; charset=UTF-8' \
  -d "$payload" \
  "$URL" 2>&1)

if [ $? -ne 0 ]; then
  echo "kel: curl failed: $response" >&2
  exit 1
fi

if ! echo "$response" | grep -q '"name"'; then
  echo "kel: unexpected response: $response" >&2
  exit 1
fi

echo "posted to space '$SPACE' as $USER_NAME"
