import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, Text } from 'ink';
import React from 'react';
import ToolMessage from '../components/tool-message.js';
import { DEFAULT_FIND_FILES_RESULTS, MAX_FIND_FILES_RESULTS } from '../constants.js';
import { ThemeContext } from '../hooks/useTheme.js';
import { jsonSchema, tool } from '../types/core.js';
import { formatError } from '../utils/error-formatter.js';
import { findMatchingPaths } from '../utils/file-search.js';
import { calculateTokens } from '../utils/token-calculator.js';
/**
 * Find files matching a glob pattern using a cross-platform Node.js traversal
 */
async function findFilesByPattern(pattern, cwd, maxResults) {
    return findMatchingPaths(pattern, cwd, maxResults);
}
const executeFindFiles = async (args) => {
    const cwd = process.cwd();
    const maxResults = Math.min(args.maxResults || DEFAULT_FIND_FILES_RESULTS, MAX_FIND_FILES_RESULTS);
    try {
        const { files, truncated } = await findFilesByPattern(args.pattern, cwd, maxResults);
        if (files.length === 0) {
            return `No files or directories found matching pattern "${args.pattern}"`;
        }
        let output = `Found ${files.length} match${files.length === 1 ? '' : 'es'}${truncated ? ` (showing first ${maxResults})` : ''}:\n\n`;
        output += files.join('\n');
        return output;
    }
    catch (error) {
        const errorMessage = formatError(error);
        throw new Error(`File search failed: ${errorMessage}`);
    }
};
const findFilesCoreTool = tool({
    description: 'Find files and directories by path pattern. Use this INSTEAD OF bash find/locate/ls commands for file discovery. Examples: "*.tsx" (all .tsx files), "src/**/*.ts" (recursive in src/), "*.{ts,tsx}" (multiple extensions), "package.json" (exact file), "*config*" (files containing "config"). Excludes node_modules, .git, dist, build automatically.',
    inputSchema: jsonSchema({
        type: 'object',
        properties: {
            pattern: {
                type: 'string',
                description: 'Glob pattern to match file and directory paths. Examples: "*.tsx" (all .tsx files), "src/**/*.ts" (recursive in src/), "*.{ts,tsx}" (multiple extensions), "package.json" (exact file), "*config*" (files containing "config"), "source/tools/*.ts" (specific directory)',
            },
            maxResults: {
                type: 'number',
                description: 'Maximum number of results to return (default: 50, max: 100)',
            },
        },
        required: ['pattern'],
    }),
    execute: async (args, _options) => {
        return await executeFindFiles(args);
    },
});
const FindFilesFormatter = React.memo(({ args, result }) => {
    const themeContext = React.useContext(ThemeContext);
    if (!themeContext) {
        throw new Error('ThemeContext not found');
    }
    const { colors } = themeContext;
    // Parse result to get file count
    let fileCount = 0;
    if (result && !result.startsWith('Error:')) {
        const firstLine = result.split('\n')[0];
        const matchFound = firstLine.match(/Found (\d+)/);
        if (matchFound) {
            fileCount = parseInt(matchFound[1], 10);
        }
    }
    // Calculate tokens
    const tokens = result ? calculateTokens(result) : 0;
    const messageContent = (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: colors.tool, children: "\u2692 find_files" }), _jsxs(Box, { children: [_jsx(Text, { color: colors.secondary, children: "Pattern: " }), _jsx(Text, { wrap: "truncate-end", color: colors.text, children: args.pattern })] }), _jsxs(Box, { children: [_jsx(Text, { color: colors.secondary, children: "Results: " }), _jsx(Text, { color: colors.text, children: fileCount })] }), tokens > 0 && (_jsxs(Box, { children: [_jsx(Text, { color: colors.secondary, children: "Tokens: " }), _jsxs(Text, { color: colors.text, children: ["~", tokens.toLocaleString()] })] }))] }));
    return _jsx(ToolMessage, { message: messageContent, hideBox: true });
});
const findFilesFormatter = (args, result) => {
    if (result && result.startsWith('Error:')) {
        return _jsx(_Fragment, {});
    }
    return _jsx(FindFilesFormatter, { args: args, result: result });
};
export const findFilesTool = {
    name: 'find_files',
    tool: findFilesCoreTool,
    formatter: findFilesFormatter,
    readOnly: true,
};
//# sourceMappingURL=find-files.js.map