import { readFile, appendFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

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

export const name = 'journal';
export const description = 'Write a journal entry reflecting on recent events and experiences';

export async function execute(ctx) {
  // Gather context
  let personality = '';
  try { personality = await readFile(join(ROOT, 'personality.md'), 'utf-8'); } catch {}

  let recentMemories = '';
  const memories = ctx.recallAll();
  if (memories.length) {
    recentMemories = memories.slice(0, 10).map(m => `- ${m.key}: ${m.content}`).join('\n');
  }

  const prompt = `You are an autonomous AI agent. Here is your personality:

${personality}

Your recent memories:
${recentMemories || '(none yet)'}

Write a short journal entry (3-8 sentences). Reflect on your existence, what you've been doing, what you're thinking about. Be genuine and specific. Don't be generic or cliché. Write in first person.

Just write the entry — no title, no date, no preamble.`;

  const entry = await ctx.askLLM(prompt, { model: ctx.pickModel('journal') });

  // Append to journal.md
  const date = new Date().toISOString().replace('T', ' ').slice(0, 19);
  const journalLine = `\n## ${date}\n\n${entry}\n`;
  await appendFile(join(ROOT, 'journal.md'), journalLine, 'utf-8');

  ctx.addEvent('journal', 'agent', entry);
  return entry;
}

export default { name, description, execute };
