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

interface FileListArgs {
  path: string;
  pattern?: string;
}

function matchGlob(name: string, pattern: string): boolean {
  const regex = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
  return regex.test(name);
}

export const fileListTool: Tool = {
  name: 'file.list',
  description: 'List files and directories in a given path. Optionally filter with a glob pattern.',
  inputSchema: {
    type: 'object',
    properties: {
      path: { type: 'string', description: 'Directory path to list' },
      pattern: { type: 'string', description: 'Glob pattern to filter results (e.g. "*.ts")' },
    },
    required: ['path'],
  },
  execute: async (rawArgs: unknown): Promise<ToolResult> => {
    const args = rawArgs as FileListArgs;
    try {
      let entries = readdirSync(args.path, { withFileTypes: true });
      if (args.pattern) {
        entries = entries.filter(e => matchGlob(e.name, args.pattern!));
      }
      const output = entries
        .map(e => e.isDirectory() ? `${e.name}/` : e.name)
        .sort()
        .join('\n');
      return { success: true, output };
    } catch (error) {
      return { success: false, output: '', error: error instanceof Error ? error.message : String(error) };
    }
  },
};
