/**
 * SectionDiff Tool — section-level diff and merge for VL files
 * Wraps src/vl/section-diff.js for use as an LLM-callable tool.
 */
import fs from 'fs/promises';
import path from 'path';
import { parseSections, sectionDiff, mergeSections } from '../vl/section-diff.js';

export function createSectionDiffTool(config) {
  return {
    description: 'Parse, diff, or merge VL files at the section level (# SectionName markers). Use to compare old vs new file content, or to merge LLM-generated content while preserving user-edited sections.',
    parameters: {
      type: 'object',
      properties: {
        action: {
          type: 'string',
          enum: ['parse', 'diff', 'merge'],
          description: 'parse: list sections in a file. diff: compare two content strings. merge: combine base + incoming with a strategy.',
        },
        file_path: {
          type: 'string',
          description: 'Relative file path (for parse action)',
        },
        old_content: {
          type: 'string',
          description: 'Old file content (for diff action)',
        },
        new_content: {
          type: 'string',
          description: 'New file content (for diff or merge action)',
        },
        base_content: {
          type: 'string',
          description: 'Base (existing) file content (for merge action)',
        },
        strategy: {
          type: 'string',
          enum: ['prefer_new', 'prefer_base', 'selective', 'smart'],
          description: 'Merge strategy. smart = only replace modified sections (recommended for incremental update)',
        },
        sections_to_replace: {
          type: 'array',
          items: { type: 'string' },
          description: 'Section names to replace (for selective strategy)',
        },
      },
      required: ['action'],
    },
    execute: async (input) => {
      try {
        switch (input.action) {
          case 'parse': {
            if (!input.file_path) return { error: 'file_path required for parse' };
            const fullPath = path.resolve(config.workDir, input.file_path);
            const content = await fs.readFile(fullPath, 'utf-8');
            const sections = parseSections(content);
            const names = [...sections.keys()];
            return { result: `Sections in ${input.file_path}:\n${names.map(n => `  # ${n}`).join('\n')}` };
          }

          case 'diff': {
            if (!input.old_content || !input.new_content) return { error: 'old_content and new_content required' };
            const diff = sectionDiff(input.old_content, input.new_content);
            const lines = [];
            if (diff.added.length)     lines.push(`Added:    ${diff.added.join(', ')}`);
            if (diff.removed.length)   lines.push(`Removed:  ${diff.removed.join(', ')}`);
            if (diff.modified.length)  lines.push(`Modified: ${diff.modified.join(', ')}`);
            if (diff.unchanged.length) lines.push(`Unchanged: ${diff.unchanged.length} section(s)`);
            return { result: lines.join('\n') || 'No differences found' };
          }

          case 'merge': {
            const base = input.base_content;
            const incoming = input.new_content;
            if (!base || !incoming) return { error: 'base_content and new_content required for merge' };

            const strategy = input.strategy || 'smart';
            let merged;
            if (strategy === 'smart') {
              const { smartMerge } = await import('../vl/section-diff.js');
              merged = smartMerge(base, incoming);
            } else {
              merged = mergeSections(base, incoming, strategy, input.sections_to_replace || []);
            }
            return { result: merged };
          }

          default:
            return { error: `Unknown action: ${input.action}` };
        }
      } catch (err) {
        return { error: err.message };
      }
    },
  };
}
