#!/usr/bin/env bash
# =============================================================================
# conversation-archive-ingest.sh — Bash wrapper around the
# conversation-archive prepare helper (Task 435).
#
# Post-Task-435 contract: the wrapper validates env (ACCOUNT_ID, USER_ID,
# NEO4J_URI, NEO4J_PASSWORD) and argv, then exec's the .mjs which runs the
# deterministic pipeline (normalise → verify participants → derive
# conversationIdentity → look up prior archive cursor → slice delta →
# sessionize → emit JSON). Classify + memory-ingest move into the dispatched
# specialist's per-turn work (driven by SKILL.md).
#
# Usage:
#   bash conversation-archive-ingest.sh <archive-path>
#         --source <whatsapp|telegram|signal|linkedin-messages|zoom-transcript|meeting-minutes|imessage|slack|x-dm|other>
#         --participant-person-ids <csv>
#         --scope <admin|public>
#         [--rebuild]
#         [--timezone <iana-zone>]
#         [--date-format <DD/MM/YY|MM/DD/YY|DD/MM/YYYY|MM/DD/YYYY>]
#
# Identity: ACCOUNT_ID + USER_ID come from the caller's env (plumbed by
# spawn-env.ts). Owner :AdminUser elementId is derived inside the .mjs.
#
# Exit 0 + one JSON line on stdout on success.
# Exit !0 + one [conversation-archive] FAIL line on stderr on failure.
# =============================================================================

set -euo pipefail

arg_fail() {
  local reason="$1"
  echo "[conversation-archive] FAIL phase=argv reason=\"${reason}\"" >&2
  exit 1
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLATFORM_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
INGEST_MJS="$SCRIPT_DIR/conversation-archive-ingest.mjs"

if [ ! -f "$INGEST_MJS" ]; then
  arg_fail "conversation-archive-ingest.mjs not found at $INGEST_MJS — run from a built install"
fi

if [ -z "${ACCOUNT_ID:-}" ]; then
  arg_fail "ACCOUNT_ID env missing — bin must be invoked under an authenticated agent context (set by spawn-env.ts)"
fi
if [ -z "${USER_ID:-}" ]; then
  arg_fail "USER_ID env missing — bin must be invoked under an authenticated user session (set by spawn-env.ts)"
fi

ARCHIVE=""
HAS_SOURCE=0
SOURCE_VAL=""
HAS_PARTICIPANTS=0
PARTICIPANTS_VAL=""
HAS_SCOPE=0
SCOPE_VAL=""

ARGS=("$@")
i=0
while [ $i -lt ${#ARGS[@]} ]; do
  a="${ARGS[$i]}"
  case "$a" in
    --source)                  HAS_SOURCE=1;       SOURCE_VAL="${ARGS[$((i + 1))]:-}";       i=$((i + 2)); continue ;;
    --participant-person-ids)  HAS_PARTICIPANTS=1; PARTICIPANTS_VAL="${ARGS[$((i + 1))]:-}"; i=$((i + 2)); continue ;;
    --scope)                   HAS_SCOPE=1;        SCOPE_VAL="${ARGS[$((i + 1))]:-}";        i=$((i + 2)); continue ;;
    --rebuild)                 i=$((i + 1)); continue ;;
    --session-gap-hours)       arg_fail "--session-gap-hours is no longer supported; gap is fixed at 8h. Use --rebuild on the prior export bytes if you need to re-classify." ;;
    --timezone|--date-format)  i=$((i + 2)); continue ;;
    --*)                       i=$((i + 2)); continue ;;
    *)
      if [ -z "$ARCHIVE" ]; then ARCHIVE="$a"; fi
      i=$((i + 1))
      continue
      ;;
  esac
done

[ -n "$ARCHIVE" ]                                                || arg_fail "missing positional <archive>"
[ "$HAS_SOURCE"       -eq 1 ] && [ -n "$SOURCE_VAL"       ]      || arg_fail "missing --source (whatsapp|telegram|signal|linkedin-messages|zoom-transcript|meeting-minutes|imessage|slack|x-dm|other)"
[ "$HAS_PARTICIPANTS" -eq 1 ] && [ -n "$PARTICIPANTS_VAL" ]      || arg_fail "missing --participant-person-ids (csv of operator-confirmed :Person/:AdminUser elementIds, owner excluded)"
[ "$HAS_SCOPE"        -eq 1 ] && [ -n "$SCOPE_VAL"        ]      || arg_fail "missing --scope (or empty value)"
case "$SCOPE_VAL" in
  admin|public) : ;;
  *) arg_fail "invalid --scope \"$SCOPE_VAL\" (admin|public)" ;;
esac

if [ -z "${NEO4J_PASSWORD:-}" ]; then
  NEO4J_PASSWORD_FILE="$PLATFORM_ROOT/config/.neo4j-password"
  if [ -f "$NEO4J_PASSWORD_FILE" ]; then
    NEO4J_PASSWORD="$(cat "$NEO4J_PASSWORD_FILE")"
    export NEO4J_PASSWORD
  else
    arg_fail "NEO4J_PASSWORD not in env and $NEO4J_PASSWORD_FILE not found"
  fi
fi

if [ -z "${NEO4J_URI:-}" ]; then
  arg_fail "NEO4J_URI not set (no default — set in env)"
fi

export NEO4J_USER="${NEO4J_USER:-neo4j}"
export MAXY_PLATFORM_ROOT="$PLATFORM_ROOT"

exec node "$INGEST_MJS" "${ARGS[@]}"
