import { readFileSync } from 'fs';
import type { Tool, ToolResult } from '../types.js';

interface FileReadArgs {
  path: string;
  offset?: number;
  limit?: number;
}

export const fileReadTool: Tool = {
  name: 'file.read',
  description: 'Read the contents of a file. Optionally read specific lines with offset and limit.',
  inputSchema: {
    type: 'object',
    properties: {
      path: { type: 'string', description: 'Absolute path to the file' },
      offset: { type: 'number', description: 'Line offset to start reading from (0-based)' },
      limit: { type: 'number', description: 'Number of lines to read' },
    },
    required: ['path'],
  },
  execute: async (rawArgs: unknown): Promise<ToolResult> => {
    const args = rawArgs as FileReadArgs;
    try {
      const content = readFileSync(args.path, 'utf-8');
      if (args.offset !== undefined || args.limit !== undefined) {
        const lines = content.split('\n');
        const start = args.offset ?? 0;
        const end = args.limit !== undefined ? start + args.limit : lines.length;
        return { success: true, output: lines.slice(start, end).join('\n') };
      }
      return { success: true, output: content };
    } catch (error) {
      return { success: false, output: '', error: error instanceof Error ? error.message : String(error) };
    }
  },
};
