/**
 * Files MCP Server - Read Operations
 *
 * Provides file system read operations.
 * Enables progressive tool discovery and efficient file exploration.
 *
 * Token Savings:
 * - Enables loading only needed files instead of all documentation
 * - Supports targeted file reading vs full context load
 */

import { callMCPTool } from "../../client.js";

export interface FileContent {
  content: string;
  path: string;
  size: number;
}

export interface DirectoryListing {
  files: string[];
  directories: string[];
  path: string;
  total: number;
}

export interface SearchResult {
  files: string[];
  count: number;
  pattern: string;
}

/**
 * Read a file from the filesystem.
 *
 * @param filePath - Absolute or relative path to file
 * @returns File content, path, and size
 *
 * @example
 * ```typescript
 * // Read a specific file
 * const file = await readFile('mawidi-site/lib/auth.ts');
 * console.log(`File size: ${file.size} characters`);
 *
 * // Search for specific pattern in code
 * if (file.content.includes('TODO')) {
 *   const todos = file.content.split('\n')
 *     .filter(line => line.includes('TODO'))
 *     .map((line, i) => `Line ${i}: ${line.trim()}`);
 *   console.log('Found TODOs:', todos);
 * }
 * ```
 */
export async function readFile(filePath: string): Promise<FileContent> {
  return callMCPTool<FileContent>("files__read_file", { path: filePath });
}

/**
 * List files in a directory.
 *
 * @param dirPath - Directory path
 * @returns List of file names, directories, and total count
 *
 * @example
 * ```typescript
 * // Explore lib directory
 * const lib = await listDirectory('mawidi-site/lib');
 * console.log(`Found ${lib.files.length} files and ${lib.directories.length} subdirectories`);
 *
 * // Find specific files
 * const authFiles = lib.files.filter(f => f.includes('auth'));
 * console.log('Auth-related files:', authFiles);
 * ```
 */
export async function listDirectory(
  dirPath: string,
): Promise<DirectoryListing> {
  return callMCPTool<DirectoryListing>("files__list_directory", {
    path: dirPath,
  });
}

/**
 * Search for files matching a pattern.
 *
 * @param dirPath - Directory to search in
 * @param pattern - Search pattern (substring match)
 * @returns List of matching file paths
 *
 * @example
 * ```typescript
 * // Find all test files
 * const tests = await searchFiles('mawidi-site', '.test.ts');
 * console.log(`Found ${tests.count} test files`);
 *
 * // Find all API routes
 * const apis = await searchFiles('mawidi-site/app/api', 'route.ts');
 * console.log('API routes:', apis.files);
 * ```
 */
export async function searchFiles(
  dirPath: string,
  pattern: string,
): Promise<SearchResult> {
  return callMCPTool<SearchResult>("files__search_files", {
    path: dirPath,
    pattern,
  });
}

export default {
  readFile,
  listDirectory,
  searchFiles,
};
