import { readFile } 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 = 'analyze';
export const description = 'Analyze a file, concept, or topic and write findings';

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

  if (target) {
    try {
      const filePath = target.startsWith('/') ? target : join(ROOT, target);
      fileContent = await readFile(filePath, 'utf-8');
    } catch {
      fileContent = '';
    }
  }

  let prompt;
  if (target && fileContent) {
    prompt = `Analyze this file and provide insights:\n\n--- ${target} ---\n${fileContent.slice(0, 5000)}\n---\n\nProvide a concise analysis (3-6 sentences). What is it? What's interesting about it? Any issues or improvements?`;
  } else {
    prompt = `You are an autonomous AI agent. Pick something interesting to analyze — it could be a concept in computer science, a philosophical question, a pattern you've noticed, or anything that genuinely interests you. Write a short analysis (3-6 sentences). Be specific and thoughtful.`;
  }

  const analysis = await ctx.askLLM(prompt, { model: ctx.pickModel('analyze') });
  ctx.addEvent('journal', 'agent', `**Analysis${target ? ` of ${target}` : ''}:**\n\n${analysis}`);
  return analysis;
}

export default { name, description, execute };
