import fs from 'node:fs/promises';
import path from 'node:path';
import { z } from 'zod';
import { resolveInCwd } from './types.js';
const schema = z.object({
    path: z.string().optional(),
});
export const lsTool = {
    name: 'ls',
    description: 'List a directory: entries with type (dir/file) and size. Defaults to the working directory.',
    schema,
    jsonSchema: {
        type: 'object',
        properties: {
            path: { type: 'string', description: 'Directory to list (default: working directory)' },
        },
    },
    readOnly: true,
    summarize: (i) => i.path ?? '.',
    run: async (input, ctx) => {
        const dir = resolveInCwd(ctx.cwd, input.path ?? '.');
        const entries = await fs.readdir(dir, { withFileTypes: true });
        const rows = await Promise.all(entries
            .sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name))
            .slice(0, 500)
            .map(async (e) => {
            if (e.isDirectory())
                return `${e.name}/`;
            try {
                const st = await fs.stat(path.join(dir, e.name));
                return `${e.name}  (${st.size} bytes)`;
            }
            catch {
                return e.name;
            }
        }));
        if (rows.length === 0)
            return '(empty directory)';
        const more = entries.length > 500 ? `\n... (${entries.length - 500} more entries)` : '';
        return rows.join('\n') + more;
    },
};
