import { readFile, readdir } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { getEvents } from '../db.mjs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..');

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

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

  if (target === 'uploads' || target === 'files') {
    // Summarize uploaded files
    const dir = join(ROOT, target === 'uploads' ? 'uploads' : 'output');
    let files;
    try { files = await readdir(dir); } catch { files = []; }
    if (!files.length) return 'No files to summarize.';

    const listing = files.slice(0, 20).join('\n');
    const prompt = `Summarize these 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 };
