#!/bin/bash
# Auditor 起動スクリプト
# launchd から2時間毎に呼ばれる。Macアクティブ時のみ Claude Code で監査実行。

set -u

AUDITOR_DIR="/Users/rk/Library/CloudStorage/GoogleDrive-ritsuha1021@gmail.com/マイドライブ/起業フォルダー/auditor"
LOG_DIR="$AUDITOR_DIR/logs"
ALERTS="$AUDITOR_DIR/ALERTS.md"
PROMPT_FILE="$AUDITOR_DIR/prompt.md"
RUN_LOG="$LOG_DIR/run.log"

mkdir -p "$LOG_DIR"

NOW=$(date '+%Y-%m-%d %H:%M:%S')

# --- アイドル判定（5分=300秒以上アイドルならスキップ） ---
idle=$(ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print int($NF/1000000000); exit}')
if [ -z "$idle" ]; then idle=0; fi

if [ "$idle" -gt 300 ]; then
  echo "[$NOW] idle=${idle}s, skip" >> "$RUN_LOG"
  exit 0
fi

echo "[$NOW] start audit, idle=${idle}s" >> "$RUN_LOG"

# --- claude CLI 探索 ---
CLAUDE_BIN=""
for candidate in "/opt/homebrew/bin/claude" "/usr/local/bin/claude" "$HOME/.local/bin/claude"; do
  if [ -x "$candidate" ]; then
    CLAUDE_BIN="$candidate"
    break
  fi
done

if [ -z "$CLAUDE_BIN" ]; then
  echo "[$NOW] ERROR: claude CLI not found" >> "$RUN_LOG"
  osascript -e 'display notification "claude CLI が見つからない。run.shのCLAUDE_BIN探索を確認" with title "Auditor 🔴 起動失敗"'
  exit 1
fi

# --- 監査実行 ---
ALERTS_BEFORE_SIZE=$(wc -c < "$ALERTS" 2>/dev/null || echo 0)

cd "$AUDITOR_DIR"
"$CLAUDE_BIN" --dangerously-skip-permissions -p "$(cat "$PROMPT_FILE")" \
  >> "$LOG_DIR/claude_$(date '+%Y%m%d_%H%M').log" 2>&1

EXIT_CODE=$?
echo "[$NOW] claude exit=$EXIT_CODE" >> "$RUN_LOG"

# --- 通知＋VSCode自動オープン判定 ---
ALERTS_AFTER_SIZE=$(wc -c < "$ALERTS" 2>/dev/null || echo 0)

if [ "$ALERTS_AFTER_SIZE" -gt "$ALERTS_BEFORE_SIZE" ]; then
  DIFF_BYTES=$((ALERTS_AFTER_SIZE - ALERTS_BEFORE_SIZE))
  NEW_CONTENT=$(tail -c "$DIFF_BYTES" "$ALERTS")

  CRITICAL_COUNT=$(echo "$NEW_CONTENT" | grep -c "🚨" || true)
  WARN_COUNT=$(echo "$NEW_CONTENT" | grep -c "⚠️" || true)
  MINOR_COUNT=$(echo "$NEW_CONTENT" | grep -c "💡" || true)

  # トップ1件サマリ抽出（最初の🚨か⚠️の1行サマリ）
  TOP_SUMMARY=$(echo "$NEW_CONTENT" | grep -E "^- (🚨|⚠️)" | head -1 | sed 's/^- //' | cut -c1-100)

  if [ "$CRITICAL_COUNT" -gt 0 ]; then
    # 🚨重大あり → 通知＋VSCodeで強制オープン
    MSG="🚨${CRITICAL_COUNT} ⚠️${WARN_COUNT} 💡${MINOR_COUNT}｜${TOP_SUMMARY}"
    osascript -e "display notification \"${MSG}\" with title \"Auditor 🔍 重大指摘\" sound name \"Submarine\""
    sleep 2
    open -a "Visual Studio Code" "$ALERTS"
    echo "[$NOW] critical=$CRITICAL_COUNT, opened VSCode" >> "$RUN_LOG"
  elif [ "$WARN_COUNT" -gt 0 ]; then
    # ⚠️警告のみ → 通知だけ
    MSG="⚠️${WARN_COUNT} 💡${MINOR_COUNT}｜${TOP_SUMMARY}"
    osascript -e "display notification \"${MSG}\" with title \"Auditor 🔍 警告\""
    echo "[$NOW] warn=$WARN_COUNT" >> "$RUN_LOG"
  else
    # 💡軽微のみ → 通知なし・ALERTS.md記録のみ
    echo "[$NOW] minor only, no notification" >> "$RUN_LOG"
  fi
fi

echo "[$NOW] done" >> "$RUN_LOG"
