import { readFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { pickRandom, readInspirationFile } from '../inspiration.mjs';

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

export const name = 'analyze';
export const description = 'Analyze a file, inspiration page, 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 {
    // Pick a random inspiration file to analyze
    const picks = await pickRandom(1);
    if (picks.length) {
      const picked = picks[0].name;
      const content = await readInspirationFile(picked, 5000);
      prompt = `You are an autonomous AI agent with a library of interactive HTML pages. Analyze this one:\n\n--- inspiration/${picked} ---\n${content}\n---\n\nProvide a concise analysis (3-6 sentences). What techniques does it use? What makes it interesting? What could you learn from it for your own creative work?`;
    } 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 };
