/**
 * MetaDiff Tool — deterministic diff of two ProjectMeta/1.0 JSONs
 * Wraps src/vl/meta-diff.js for use as an LLM-callable tool.
 */
import fs from 'fs/promises';
import path from 'path';
import { computeMetaDiff } from '../vl/meta-diff.js';

export function createMetaDiffTool(config, symbolIndex = null) {
  return {
    description: 'Deterministically diff two ProjectMeta/1.0 JSON objects to find added/removed/modified sections, components, services, and tables. Returns affected file list and cascade impact. Much faster and more reliable than asking the LLM to compute diffs.',
    parameters: {
      type: 'object',
      properties: {
        old_meta: {
          description: 'Old ProjectMeta object, or "current" to load from .vl-code/ProjectMeta.json',
        },
        new_meta: {
          type: 'object',
          description: 'New ProjectMeta object to compare against',
        },
        include_cascade: {
          type: 'boolean',
          description: 'Whether to compute cascade impact via symbol cross-references (default: true)',
        },
      },
      required: ['old_meta', 'new_meta'],
    },
    execute: async (input) => {
      let oldMeta = input.old_meta;

      if (oldMeta === 'current') {
        try {
          const metaPath = path.join(config.workDir, '.vl-code', 'ProjectMeta.json');
          oldMeta = JSON.parse(await fs.readFile(metaPath, 'utf-8'));
        } catch {
          return { error: 'Could not read .vl-code/ProjectMeta.json. Run VLMetadata first.' };
        }
      }

      if (!oldMeta || !input.new_meta) {
        return { error: 'old_meta and new_meta are required' };
      }

      const useSymbolIndex = input.include_cascade !== false ? symbolIndex : null;
      const diff = computeMetaDiff(oldMeta, input.new_meta, useSymbolIndex);

      return { result: JSON.stringify(diff, null, 2) };
    },
  };
}
