#!/usr/bin/env bash
# List or mark pending verification outbound mail jobs for Chief of Staff / Outlook.
# Usage:
#   ./deploy/flush-verify-mail.sh              # print pending jobs as JSON array
#   ./deploy/flush-verify-mail.sh --mark-sent <id> [<id>...]
#   ./deploy/flush-verify-mail.sh --pending-file  # path to jsonl
set -euo pipefail
ROOT=/home/box/zen-lead-form
FILE="$ROOT/data/outbound-mail.jsonl"
SIGNAL="$ROOT/data/outbound-mail.pending"

mkdir -p "$ROOT/data"
touch "$FILE"
chmod 600 "$FILE" 2>/dev/null || true

if [[ "${1:-}" == "--pending-file" ]]; then
  echo "$FILE"
  exit 0
fi

if [[ "${1:-}" == "--mark-sent" ]]; then
  shift
  if [[ $# -lt 1 ]]; then
    echo "usage: $0 --mark-sent <id> [<id>...]" >&2
    exit 2
  fi
  tmp=$(mktemp)
  python3 - "$FILE" "$tmp" "$@" <<'PY'
import json, sys
path, out = sys.argv[1], sys.argv[2]
ids = set(sys.argv[3:])
lines = []
try:
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                job = json.loads(line)
            except json.JSONDecodeError:
                lines.append(line)
                continue
            if job.get("id") in ids and job.get("status") == "pending":
                job["status"] = "sent"
            lines.append(json.dumps(job, ensure_ascii=False))
except FileNotFoundError:
    pass
with open(out, "w", encoding="utf-8") as f:
    for line in lines:
        f.write(line + "\n")
PY
  mv "$tmp" "$FILE"
  chmod 600 "$FILE"
  # clear signal if no pending left
  if ! grep -q '"status":"pending"' "$FILE" 2>/dev/null; then
    rm -f "$SIGNAL"
  fi
  echo "{\"ok\":true,\"marked\":$(printf '%s\n' "$@" | python3 -c 'import json,sys; print(json.dumps([l.strip() for l in sys.stdin if l.strip()]))')}"
  exit 0
fi

# Default: print pending jobs as JSON array
python3 - "$FILE" <<'PY'
import json, sys
path = sys.argv[1]
pending = []
try:
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                job = json.loads(line)
            except json.JSONDecodeError:
                continue
            if job.get("status") == "pending":
                pending.append(job)
except FileNotFoundError:
    pass
print(json.dumps(pending, ensure_ascii=False, indent=2))
PY
