#!/usr/bin/env bash
set -euo pipefail

# Email summary script for OpenClaw
# Sends a short HTML summary of unread messages received since last run
# Enhanced: compute a short summary of the full email body using the local OpenClaw assistant

WORKDIR="$HOME/.openclaw/workspace"
STATE_FILE="$WORKDIR/last_email_summary_ts"
TMP_DIR="/tmp"
OUT_HTML="$TMP_DIR/email_summary.html"
OUT_PLAIN="$TMP_DIR/email_summary.txt"
ACCOUNT="mikael.sundgren@gmail.com"
RECIPIENT="mikael@boid.se"
MAX_THREADS=200
DRY_RUN=${DRY_RUN:-0}

# Ensure workspace exists
mkdir -p "$WORKDIR"
mkdir -p "$WORKDIR/logs"

# Source the user's profile so cron runs inherit expected env (GOG_KEYRING_PASSWORD, PATH, etc.)
if [[ -f "$HOME/.profile" ]]; then
  # shellcheck source=/dev/null
  . "$HOME/.profile"
fi

# Log everything for debugging when run by cron
LOGFILE="$WORKDIR/logs/email_summary.log"
exec >>"$LOGFILE" 2>&1
echo "---- Run at $(date -Is) ----"

# Read last timestamp (unix seconds). If missing, default to 24 hours ago
if [[ -f "$STATE_FILE" ]]; then
  LAST_TS=$(cat "$STATE_FILE")
else
  LAST_TS=$(( $(date +%s) - 24*3600 ))
fi

# Gmail 'after' expects unix seconds
QUERY="is:unread after:$LAST_TS"

echo "Using ACCOUNT=$ACCOUNT RECIPIENT=$RECIPIENT QUERY='$QUERY'"
export GOG_ACCOUNT="$ACCOUNT"

# Fetch threads
threads_json=$(gog gmail search "$QUERY" --max $MAX_THREADS --json --account "$ACCOUNT" 2>&1 || true)

echo "Search result length: ${#threads_json} bytes"
# If no threads or empty, update timestamp and exit
if [[ -z "$threads_json" || "$threads_json" == "null" ]]; then
  echo "No threads found. Updating state timestamp and exiting."
  date +%s > "$STATE_FILE"
  echo "Updated $STATE_FILE to $(cat $STATE_FILE)"
  echo "---- End run ----"
  exit 0
fi

count=$(echo "$threads_json" | jq '.threads | length // 0')
if [[ "$count" -eq 0 ]]; then
  echo "Zero threads in result. Updating state timestamp and exiting."
  date +%s > "$STATE_FILE"
  echo "Updated $STATE_FILE to $(cat $STATE_FILE)"
  echo "---- End run ----"
  exit 0
fi

echo "Found $count threads. Preparing summaries."
# Prepare HTML and plain summaries
cat > "$OUT_HTML" <<'HTML'
<html><body style="font-family:system-ui,Helvetica,Arial,sans-serif;color:#111;">
<h2>Automatisk sammanfattning: olästa mejl</h2>
HTML

printf "Automatisk sammanfattning: olästa mejl\n\n" > "$OUT_PLAIN"

# Function: compute_summary
# Uses the local OpenClaw assistant via CLI to compute a short summary of full text.
# Falls back to the snippet if summariser is unavailable.
compute_summary() {
  local textfile="$1"
  local out
  if command -v openclaw >/dev/null 2>&1; then
    # Use openclaw's local assistant to summarise. Request a short bulleted summary (1-2 sentences).
    # We run in a safe, non-interactive mode expecting the CLI to return plaintext.
    out=$(openclaw assistant summarize --stdin < "$textfile" 2>/dev/null || true)
  fi
  if [[ -z "${out// /}" ]]; then
    # fallback: take first 2 lines and trim
    out=$(head -n 6 "$textfile" | sed 's/\n/ /g' | cut -c1-400)
  fi
  echo "$out"
}

# For each thread, fetch first message and append
echo "$threads_json" | jq -r '.threads[]?.id' | while read -r tid; do
  # Get message JSON
  msgfile="$TMP_DIR/msg_$tid.json"
  echo "Fetching message $tid"
  gog gmail get "$tid" --account "$ACCOUNT" --json > "$msgfile" 2>&1 || { echo "Failed to fetch $tid"; continue; }

  # Extract fields safely
  subject=$(jq -r '.message.payload.headers[]? | select(.name=="Subject") | .value' "$msgfile" 2>/dev/null || echo "(no subject)")
  from=$(jq -r '.message.payload.headers[]? | select(.name=="From") | .value' "$msgfile" 2>/dev/null || echo "")
  date_hdr=$(jq -r '.message.payload.headers[]? | select(.name=="Date") | .value' "$msgfile" 2>/dev/null || echo "")

  # Try to extract full plain text body; fallback to snippet
  body_text="$TMP_DIR/body_$tid.txt"
  jq -r '(.message.payload.parts[]? | select(.mimeType=="text/plain") | .body.data) // .message.payload.body.data // ""' "$msgfile" | base64 --decode 2>/dev/null > "$body_text" || true
  if [[ ! -s "$body_text" ]]; then
    # fallback to snippet
    snippet=$(jq -r '.message.snippet // ""' "$msgfile" | sed 's/\n/ /g' | cut -c1-600)
    echo "$snippet" > "$body_text"
  fi

  # Compute a concise summary using the local assistant (or fallback)
  computed_summary=$(compute_summary "$body_text" | sed 's/"/\"/g')

  # Decide importance/action
  has_attachments=$(jq -r '.message.payload.parts[]? | select(.filename != null and .filename != "") | .filename' "$msgfile" | wc -l || true)
  subject_lower=$(echo "$subject" | tr '[:upper:]' '[:lower:]')
  importance="Low"
  action="Read / Reply"
  if [[ $has_attachments -gt 0 ]]; then importance="High"; fi
  if echo "$subject_lower" | grep -E "invoice|payment|urgent|action required|password|verification|code|reset" >/dev/null; then importance="High"; fi
  if echo "$from" | grep -Ei "adobe|bank|noreply@boss|boss@" >/dev/null; then importance="High"; fi

  # Append HTML
  cat >> "$OUT_HTML" <<HTML
  <hr style="border:none;border-top:1px solid #eee;margin:16px 0;"/>
  <h3 style="margin:6px 0;">${subject}</h3>
  <div style="color:#666;margin-bottom:6px;">${from} — ${date_hdr}</div>
  <ul style="margin:8px 0 12px;color:#222;">
    <li><strong>Summary:</strong> ${computed_summary}</li>
    <li><strong>Recommendation:</strong> ${action}</li>
    <li><strong>Importance:</strong> ${importance}</li>
  </ul>
  <div style="background:#f7f7f8;padding:8px;border-radius:6px;color:#333;display:inline-block;font-size:13px;">Suggested action: <strong>${action}</strong></div>
HTML

  # Append plain
  printf -- "---\nSubject: %s\nFrom: %s\nDate: %s\n\nSummary: %s\nSuggested action: %s\nImportance: %s\n\n" "$subject" "$from" "$date_hdr" "$computed_summary" "$action" "$importance" >> "$OUT_PLAIN"

done

# Finish HTML
cat >> "$OUT_HTML" <<'HTML'
<hr style="border:none;border-top:1px solid #eee;margin:16px 0;"/>
<p style="color:#666;font-size:13px;margin-top:12px;">Generated by OpenClaw assistant.</p>
</body></html>
HTML

# Send if there are items
if [[ $(wc -c < "$OUT_PLAIN") -gt 0 ]]; then
  echo "Prepared summary content (size: $(wc -c < $OUT_PLAIN) bytes)"
  if [[ "$DRY_RUN" -eq 1 ]]; then
    echo "DRY_RUN=1; not sending. Output saved to $OUT_PLAIN and $OUT_HTML"
  else
    echo "Sending summary to $RECIPIENT"
    gog gmail send --to "$RECIPIENT" --subject "Automatisk: olästa mejl sedan senaste sammanfattning" --body-file "$OUT_PLAIN" --body-html "$(cat $OUT_HTML)" --account "$ACCOUNT" 2>&1 || echo "Send failed (see above)"
  fi
else
  echo "No content to send after processing."
fi

# Update state timestamp to now
date +%s > "$STATE_FILE"
echo "Updated $STATE_FILE to $(cat $STATE_FILE)"

echo "---- End run ----"

exit 0
