import fs from 'node:fs/promises';
import { z } from 'zod';
import { resolveInCwd, truncateOutput } from './types.js';
const schema = z.object({
    path: z.string().min(1),
    offset: z.number().int().positive().optional(),
    limit: z.number().int().positive().optional(),
});
export const readTool = {
    name: 'read_file',
    description: 'Read a file and return its contents with line numbers (format: "  12|content"). ' +
        'Optionally pass offset (1-based start line) and limit (number of lines). ' +
        'Always read a file before editing it.',
    schema,
    jsonSchema: {
        type: 'object',
        properties: {
            path: { type: 'string', description: 'File path (absolute or relative to cwd)' },
            offset: { type: 'number', description: '1-based line to start from' },
            limit: { type: 'number', description: 'Max lines to return' },
        },
        required: ['path'],
    },
    readOnly: true,
    summarize: (i) => i.path,
    run: async (input, ctx) => {
        const file = resolveInCwd(ctx.cwd, input.path);
        const raw = await fs.readFile(file, 'utf8');
        const lines = raw.split('\n');
        const start = (input.offset ?? 1) - 1;
        const end = input.limit ? start + input.limit : lines.length;
        const slice = lines.slice(start, end);
        const width = String(start + slice.length).length;
        const numbered = slice
            .map((l, i) => `${String(start + i + 1).padStart(width)}|${l}`)
            .join('\n');
        const suffix = end < lines.length ? `\n... (${lines.length - end} more lines, use offset to continue)` : '';
        return truncateOutput(numbered) + suffix;
    },
};
