#!/usr/bin/env bash
# Desk visual assist API · capture · OCR · act on error windows
# Full access path for Grok/agent to SEE and FIX UI (Claws etc.)
#
#   desk-assist ocr [screen|claws|window NAME]
#   desk-assist see claws          # OCR claws (alias)
#   desk-assist claws-fix         # fix incomplete IMAP + theme + receive
#   desk-assist claws-close-error  # close Claws Error dialog via xdotool
#   desk-assist claws-rebuild      # best-effort: focus claws, hint rebuild
#   desk-assist status             # paths + last OCR summary
#
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
export DISPLAY="${DISPLAY:-:0}"
export SUDO_PASS="${SUDO_PASS:-mememe}"
export SUDO_ASKPASS="${SUDO_ASKPASS:-$ROOT/Build/sudo-askpass.sh}"

cmd="${1:-status}"
shift || true

ocr() {
  bash "$ROOT/Build/desk-ocr.sh" "$@"
}

claws_close_error() {
  command -v xdotool >/dev/null || { echo "need xdotool"; return 1; }
  # Error dialog title often "Error" under Claws
  local ids
  ids=$(xdotool search --name 'Error' 2>/dev/null || true)
  if [[ -z "$ids" ]]; then
    ids=$(xdotool search --name 'incomplete' 2>/dev/null || true)
  fi
  if [[ -z "$ids" ]]; then
    echo "no Error dialog found"
    return 0
  fi
  for id in $ids; do
    echo "close error window $id"
    xdotool windowactivate --sync "$id" 2>/dev/null || true
    # try click Close button region / press Escape / Alt+F4
    xdotool key --window "$id" Escape 2>/dev/null || true
    sleep 0.2
    xdotool key --window "$id" Return 2>/dev/null || true
    sleep 0.2
    xdotool windowkill "$id" 2>/dev/null || true
  done
  # OCR after
  ocr screen | tail -20
}

claws_fix() {
  chmod +x "$ROOT/Build/claws-fix-mailbox.sh" 2>/dev/null || true
  bash "$ROOT/Build/claws-fix-mailbox.sh" "$@"
  # redeploy safe CSS
  local S="$HOME/Projects/Santa"
  if [[ -d "$S/gtk-3.0" ]]; then
    mkdir -p "$S/.xdg-config/gtk-3.0"
    cp -f "$S/gtk-3.0/gtk.css" "$S/.xdg-config/gtk-3.0/gtk.css"
  fi
  claws_close_error || true
  if pgrep -x claws-mail >/dev/null 2>&1; then
    claws-mail --online 2>/dev/null || true
    claws-mail --receive-all 2>/dev/null || true
  else
    if [[ -x "$HOME/Projects/Santa/bin/claws-santa" ]]; then
      nohup "$HOME/Projects/Santa/bin/claws-santa" >>/tmp/claws-santa.log 2>&1 &
      sleep 2
    fi
  fi
  ocr claws || ocr screen
}

status() {
  echo "=== desk-assist · visual API ==="
  echo "ocr:     $ROOT/Build/desk-ocr.sh"
  echo "fix:     $ROOT/Build/claws-fix-mailbox.sh"
  echo "latest:  $OUT/desk-ocr-latest.png"
  echo "         $OUT/desk-ocr-latest.txt"
  echo "json:    $OUT/desk-ocr-latest.json"
  if [[ -f "$OUT/desk-ocr-latest.json" ]]; then
    python3 -c "import json;d=json.load(open('$OUT/desk-ocr-latest.json'));print('last OCR chars',d.get('chars'),'ts',d.get('ts'));print((d.get('preview') or '')[:400])"
  fi
  pgrep -x claws-mail >/dev/null && echo "claws: RUNNING" || echo "claws: not running"
  echo "law: full visual assist · error windows included · sudo mememe no polkit"
}

case "$cmd" in
  ocr|see) ocr "${1:-screen}" "${2:-}" ;;
  claws|claws-ocr) ocr claws ;;
  claws-fix|fix-mailbox|fix) claws_fix "$@" ;;
  claws-close-error|close-error) claws_close_error ;;
  claws-rebuild)
    echo "Claws has no stable CLI for rebuild folder tree."
    echo "After IMAP password OK: right-click account → Rebuild folder tree"
    claws_fix "$@"
    ;;
  status|st) status ;;
  *)
    echo "usage: desk-assist ocr|claws-fix|claws-close-error|status"
    status
    ;;
esac
