export const name = 'vision';
export const description = 'Analyze and describe images using vision AI';
export async function execute(ctx) {
  // ctx has: askLLM, pickModel, remember, recall, recallAll, addEvent, writeOutputFile, args
  const { describeImage, isVisionAvailable, getImageMetadata } = await import('../multimodal/vision.mjs');
  const { resolve, basename } = await import('path');
  const { existsSync } = await import('fs');
  const { getWorkspaceRoot } = await import('../workspace.mjs');

  let target = ctx.args?.target || ctx.args?.topic || '';
  if (!target) {
    ctx.addEvent('skill', 'agent', 'Vision skill: no target file specified');
    return { success: false, error: 'No target file specified' };
  }

  // If target doesn't look like a file path (contains spaces, no extension, etc.),
  // try to extract a filename from it.
  if (!existsSync(target)) {
    // Try extracting a filename pattern from the target text
    const filenameMatch = target.match(/\b([\w.-]+\.(?:png|jpg|jpeg|gif|webp|bmp|svg))\b/i);
    if (filenameMatch) {
      target = filenameMatch[1];
    }
  }

  // Resolve relative filenames against the workspace directory
  if (!existsSync(target)) {
    const wsRoot = getWorkspaceRoot();
    const inWorkspace = resolve(wsRoot, basename(target));
    if (existsSync(inWorkspace)) {
      target = inWorkspace;
    }
  }

  try {
    const result = await describeImage(target, ctx.args?.prompt || 'Describe this image in detail.');
    ctx.addEvent('skill', 'agent', `Vision analysis: ${result.metadata.filename} → ${result.description.slice(0, 200)}`);
    return { success: true, ...result };
  } catch (err) {
    ctx.addEvent('skill', 'agent', `Vision skill failed: ${err.message}`);
    return { success: false, error: err.message };
  }
}
