import { getEvents } from '../db.mjs';
import { listWorkspaceFiles } from '../workspace.mjs';

export const name = 'summarize';
export const description = 'Summarize recent events, uploaded files, or conversations';

const FILE_EXTS = new Set(['.txt', '.md', '.html', '.json']);

export async function execute(ctx) {
  const target = ctx.args?.target;

  if (target === 'uploads' || target === 'files') {
    // Summarize files in the active workspace directory
    const allFiles = await listWorkspaceFiles(ctx.getActiveWorkspaceId?.());
    const files = allFiles
      .filter(f => FILE_EXTS.has(f.name.slice(f.name.lastIndexOf('.'))))
      .slice(0, 20);
    if (!files.length) return 'No files to summarize.';

    const listing = files.map(f => `${f.name} (${f.size} bytes, modified ${f.modified})`).join('\n');
    const prompt = `Summarize these workspace files in 2-3 sentences:\n${listing}`;
    const summary = await ctx.askLLM(prompt, { model: ctx.pickModel('summarize') });
    ctx.addEvent('system', 'agent', `**File Summary:**\n${summary}`);
    return summary;
  }

  // Default: summarize recent events
  const events = getEvents({ limit: 30 });
  if (!events.length) return 'No recent events to summarize.';

  const eventLog = events.reverse().map(e =>
    `[${e.created_at}] ${e.type}/${e.source}: ${e.content.slice(0, 200)}`
  ).join('\n');

  const prompt = `Summarize what's been happening recently based on these events. Be concise (3-5 sentences):\n\n${eventLog}`;
  const summary = await ctx.askLLM(prompt, { model: ctx.pickModel('summarize') });
  ctx.addEvent('system', 'agent', `**Recent Activity Summary:**\n\n${summary}`);
  return summary;
}

export default { name, description, execute };
