/**
 * Notes AI summary backfill.
 *
 * On startup, scans notes with a null ai_summary and generates summaries
 * via the backend `POST /api/v1/agents/notes/summarize` endpoint.
 *
 * - Throttled to 1 request/second to avoid rate-limiting.
 * - Idempotent: notes that already have an aiSummary are skipped.
 * - Offline-safe: if the backend is unreachable the run is skipped entirely;
 *   the next startup will retry.
 */

import { eq, isNull } from 'drizzle-orm';
import { getDb } from './index';
import { notes } from './schema';
import { getBackendClient } from '../api/backend-client';

const THROTTLE_MS = 1_000;

export async function backfillNoteSummaries(): Promise<void> {
  const client = getBackendClient();

  const isOnline = await client.isOnline().catch(() => false);
  if (!isOnline) {
    console.log('[NotesBackfill] Backend offline — skipping aiSummary backfill.');
    return;
  }

  const pending = getDb()
    .select({ id: notes.id, title: notes.title, content: notes.content })
    .from(notes)
    .where(isNull(notes.aiSummary))
    .all();

  if (pending.length === 0) {
    console.log('[NotesBackfill] All notes have aiSummary — nothing to backfill.');
    return;
  }

  console.log(`[NotesBackfill] Generating aiSummary for ${pending.length} note(s)…`);
  let success = 0;

  for (let i = 0; i < pending.length; i++) {
    const note = pending[i]!;
    try {
      const result = await client.proxyPost<{ summary: string }>(
        '/api/v1/agents/notes/summarize',
        { title: note.title, content: note.content },
      );
      const summary = result.summary?.trim() ?? '';
      if (summary) {
        getDb()
          .update(notes)
          .set({ aiSummary: summary, aiSummaryUpdatedAt: Date.now() })
          .where(eq(notes.id, note.id))
          .run();
        success++;
      }
    } catch (err) {
      console.warn(`[NotesBackfill] Failed for note ${note.id}:`, err);
    }

    if (i < pending.length - 1) {
      await new Promise<void>((r) => setTimeout(r, THROTTLE_MS));
    }
  }

  console.log(`[NotesBackfill] Done: ${success}/${pending.length} summaries generated.`);
}
