"use strict";
// =============================================================================
// Pure file-system API — no ToolContext coupling.
// Takes a workspaceRoot string and safely-resolves paths beneath it.
// =============================================================================
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.readFile = readFile;
exports.writeFile = writeFile;
exports.replaceInFile = replaceInFile;
exports.listDirectory = listDirectory;
exports.findFiles = findFiles;
exports.searchCode = searchCode;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const cp = __importStar(require("child_process"));
const util = __importStar(require("util"));
const minimatch_1 = require("minimatch");
const utils_1 = require("./utils");
const execAsync = util.promisify(cp.exec);
async function readFile(workspaceRoot, relPath) {
    const abs = (0, utils_1.safeResolve)(workspaceRoot, relPath);
    try {
        return fs.readFileSync(abs, 'utf8');
    }
    catch {
        return { error: `File not found: ${relPath}` };
    }
}
async function writeFile(workspaceRoot, relPath, content) {
    const abs = (0, utils_1.safeResolve)(workspaceRoot, relPath);
    fs.mkdirSync(path.dirname(abs), { recursive: true });
    fs.writeFileSync(abs, content, 'utf8');
    return { success: true, path: relPath, bytes: Buffer.byteLength(content) };
}
async function replaceInFile(workspaceRoot, relPath, oldContent, newContent) {
    const abs = (0, utils_1.safeResolve)(workspaceRoot, relPath);
    const current = fs.readFileSync(abs, 'utf8');
    if (!current.includes(oldContent)) {
        return { error: 'old_content not found in file. Read the file again to get the current content.' };
    }
    fs.writeFileSync(abs, current.replace(oldContent, newContent), 'utf8');
    return { success: true, path: relPath };
}
async function listDirectory(workspaceRoot, relPath) {
    const abs = (0, utils_1.safeResolve)(workspaceRoot, relPath);
    try {
        const entries = fs.readdirSync(abs, { withFileTypes: true });
        return entries
            .filter(e => !utils_1.EXCLUDED.has(e.name))
            .map(e => e.isDirectory() ? `${e.name}/` : e.name);
    }
    catch {
        return { error: `Directory not found: ${relPath}` };
    }
}
async function findFiles(workspaceRoot, pattern) {
    const matcher = new minimatch_1.Minimatch(pattern, { dot: false });
    const results = [];
    function walk(dir) {
        if (results.length >= 200)
            return;
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const e of entries) {
            if (utils_1.EXCLUDED.has(e.name))
                continue;
            const abs = path.join(dir, e.name);
            const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
            if (e.isDirectory()) {
                walk(abs);
            }
            else if (matcher.match(rel)) {
                results.push(rel);
            }
        }
    }
    walk(workspaceRoot);
    return { files: results, truncated: results.length >= 200 };
}
async function searchCode(workspaceRoot, query, fileExtensions) {
    const globPatterns = fileExtensions?.map(e => `*.${e}`) || [];
    const rgArgs = ['--line-number', '--no-heading', '--color=never', '--max-count=30'];
    for (const ex of utils_1.EXCLUDED) {
        rgArgs.push('--glob', `!${ex}`);
    }
    if (globPatterns.length > 0) {
        for (const g of globPatterns)
            rgArgs.push('--glob', g);
    }
    rgArgs.push('--fixed-strings', query, workspaceRoot);
    try {
        const { stdout } = await execAsync(`rg ${rgArgs.map(a => `'${a}'`).join(' ')}`, {
            cwd: workspaceRoot, timeout: 15000,
        });
        return stdout.trim().split('\n').filter(Boolean).map(line => {
            const m = line.match(/^(.+?):(\d+):(.*)$/);
            if (!m)
                return null;
            return {
                file: path.relative(workspaceRoot, m[1]).split(path.sep).join('/'),
                line: parseInt(m[2]),
                content: m[3].trim(),
            };
        }).filter(Boolean);
    }
    catch (err) {
        if (err.code === 1)
            return []; // ripgrep exit 1 = no matches
        return { error: `Search failed: ${err.message}` };
    }
}
