import fs from 'node:fs';
import path from 'node:path';
import { tool } from 'ai';
import { z } from 'zod';
import { readTextFile, relativeWorkspacePath, resolveWorkspacePath, shouldIgnorePath, truncateText, workspaceRoot } from './workspace-utils.js';
function visitFiles(targetPath, results) {
    if (shouldIgnorePath(targetPath)) {
        return;
    }
    const stats = fs.statSync(targetPath);
    if (stats.isFile()) {
        results.push(targetPath);
        return;
    }
    for (const entry of fs.readdirSync(targetPath, { withFileTypes: true })) {
        visitFiles(path.join(targetPath, entry.name), results);
    }
}
export function createSearchWorkspaceTool(_observer) {
    return tool({
        description: 'Search text across workspace files. Use this to find workflow names, maps, node properties, or n8nac config entries.',
        parameters: z.object({
            query: z.string().min(1).describe('Plain-text or regular-expression search query.'),
            path: z.string().default('.').describe('Workspace-relative root path to search in.'),
            isRegexp: z.boolean().default(false).describe('Interpret query as a JavaScript regular expression.'),
            maxResults: z.number().int().min(1).max(200).default(50).describe('Maximum number of matches to return.'),
        }),
        execute: async ({ query, path: inputPath, isRegexp, maxResults }) => {
            const targetPath = resolveWorkspacePath(inputPath);
            try {
                fs.statSync(targetPath);
            }
            catch (error) {
                return {
                    query,
                    matches: [],
                    ok: false,
                    path: inputPath,
                    error: error instanceof Error ? error.message : String(error),
                };
            }
            const files = [];
            visitFiles(targetPath, files);
            const matcher = isRegexp ? new RegExp(query, 'i') : null;
            const matches = [];
            for (const filePath of files) {
                if (matches.length >= maxResults) {
                    break;
                }
                if (path.relative(workspaceRoot(), filePath).startsWith('node_modules')) {
                    continue;
                }
                let text;
                try {
                    text = readTextFile(filePath);
                }
                catch {
                    continue;
                }
                const lines = text.split(/\r?\n/);
                for (let index = 0; index < lines.length; index += 1) {
                    const line = lines[index];
                    const found = matcher ? matcher.test(line) : line.toLowerCase().includes(query.toLowerCase());
                    if (!found) {
                        continue;
                    }
                    matches.push({
                        path: relativeWorkspacePath(filePath),
                        line: index + 1,
                        text: truncateText(line, 300),
                    });
                    if (matches.length >= maxResults) {
                        break;
                    }
                }
            }
            return {
                ok: true,
                path: relativeWorkspacePath(targetPath),
                query,
                matches,
            };
        },
    });
}
//# sourceMappingURL=search-workspace.js.map