"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeAsciiDirectoryStructure = makeAsciiDirectoryStructure;
exports.getFileContents = getFileContents;
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
/**
 * A minimal LRU-based file cache to store file contents keyed by absolute path.
 * We store (mtime, size, content). If a file's mtime or size changes, we consider
 * the cache invalid and re-read.
 */
class LRUFileCache {
    constructor(maxSize) {
        this.maxSize = maxSize;
        this.cache = new Map();
    }
    /**
     * Retrieves the cached entry for the given path, if it exists.
     * If found, we re-insert it in the map to mark it as recently used.
     */
    get(key) {
        const entry = this.cache.get(key);
        if (entry) {
            // Re-insert to maintain recency
            this.cache.delete(key);
            this.cache.set(key, entry);
        }
        return entry;
    }
    /**
     * Insert or update an entry in the cache.
     */
    set(key, entry) {
        // if key already in map, delete it so that insertion below sets recency.
        if (this.cache.has(key)) {
            this.cache.delete(key);
        }
        this.cache.set(key, entry);
        // If over capacity, evict the least recently used entry.
        if (this.cache.size > this.maxSize) {
            const firstKey = this.cache.keys().next();
            if (!firstKey.done) {
                this.cache.delete(firstKey.value);
            }
        }
    }
    /**
     * Remove an entry from the cache.
     */
    delete(key) {
        this.cache.delete(key);
    }
    /**
     * Returns all keys in the cache (for pruning old files, etc.).
     */
    keys() {
        return this.cache.keys();
    }
}
// Environment-based defaults
const MAX_CACHE_ENTRIES = parseInt(process.env["TENX_FILE_CACHE_MAX_ENTRIES"] || "1000", 10);
// Global LRU file cache instance.
const FILE_CONTENTS_CACHE = new LRUFileCache(MAX_CACHE_ENTRIES);
/**
 * Recursively builds an ASCII representation of a directory structure, given a list
 * of file paths.
 */
function makeAsciiDirectoryStructure(rootPath, filePaths) {
    const root = path_1.default.resolve(rootPath);
    const tree = {};
    for (const file of filePaths) {
        const resolved = path_1.default.resolve(rootPath, file);
        let relPath;
        try {
            const rp = path_1.default.relative(root, resolved);
            // If it's outside of root, skip.
            if (rp.startsWith("..")) {
                continue;
            }
            relPath = rp;
        }
        catch (_a) {
            continue;
        }
        const parts = relPath.split(path_1.default.sep);
        let current = tree;
        for (let i = 0; i < parts.length; i++) {
            const part = parts[i];
            if (!part) {
                continue;
            }
            if (i === parts.length - 1) {
                // file
                current[part] = null;
            }
            else {
                if (!current[part]) {
                    current[part] = {};
                }
                current = current[part];
            }
        }
    }
    const lines = [root];
    function recurse(node, prefix) {
        const entries = Object.keys(node).sort((a, b) => {
            // Directories first, then files
            const aIsDir = node[a] != null;
            const bIsDir = node[b] != null;
            if (aIsDir && !bIsDir) {
                return -1;
            }
            if (!aIsDir && bIsDir) {
                return 1;
            }
            return a.localeCompare(b);
        });
        for (let i = 0; i < entries.length; i++) {
            const entry = entries[i];
            if (!entry) {
                continue;
            }
            const isLast = i === entries.length - 1;
            const connector = isLast ? "└──" : "├──";
            const isDir = node[entry] != null;
            lines.push(`${prefix}${connector} ${entry}`);
            if (isDir) {
                const newPrefix = prefix + (isLast ? "    " : "│   ");
                recurse(node[entry], newPrefix);
            }
        }
    }
    recurse(tree, "");
    return lines.join("\n");
}
function shouldIgnorePath(...args) {
    return false;
}
/**
 * Recursively collects all files under rootPath that are not ignored, skipping symlinks.
 * Then for each file, we check if it's in the LRU cache. If not or changed, we read it.
 * Returns an array of FileContent.
 *
 * After collecting, we remove from the cache any file that no longer exists in the BFS.
 */
function getFileContents(rootPath, compiledPatterns) {
    return __awaiter(this, void 0, void 0, function* () {
        const root = path_1.default.resolve(rootPath);
        const candidateFiles = [];
        // BFS queue of directories
        const queue = [root];
        while (queue.length > 0) {
            const currentDir = queue.pop();
            let dirents = [];
            try {
                dirents = yield promises_1.default.readdir(currentDir, { withFileTypes: true });
            }
            catch (_a) {
                continue;
            }
            for (const dirent of dirents) {
                try {
                    const resolved = path_1.default.resolve(currentDir, dirent.name);
                    // skip symlinks
                    const lstat = yield promises_1.default.lstat(resolved);
                    if (lstat.isSymbolicLink()) {
                        continue;
                    }
                    if (dirent.isDirectory()) {
                        // check if ignored
                        if (!shouldIgnorePath(resolved, compiledPatterns)) {
                            queue.push(resolved);
                        }
                    }
                    else if (dirent.isFile()) {
                        // check if ignored
                        if (!shouldIgnorePath(resolved, compiledPatterns)) {
                            candidateFiles.push(resolved);
                        }
                    }
                }
                catch (_b) {
                    // skip
                }
            }
        }
        // We'll read the stat for each candidate file, see if we can skip reading from cache.
        const results = [];
        // We'll keep track of which files we actually see.
        const seenPaths = new Set();
        yield Promise.all(candidateFiles.map((filePath) => __awaiter(this, void 0, void 0, function* () {
            seenPaths.add(filePath);
            let st = null;
            try {
                st = yield promises_1.default.stat(filePath);
            }
            catch (_a) {
                return;
            }
            if (!st) {
                return;
            }
            const cEntry = FILE_CONTENTS_CACHE.get(filePath);
            if (cEntry &&
                Math.abs(cEntry.mtime - st.mtime.getTime()) < 1 &&
                cEntry.size === st.size) {
                // same mtime, same size => use cache
                results.push({ path: filePath, content: cEntry.content });
            }
            else {
                // read file
                try {
                    const buf = yield promises_1.default.readFile(filePath);
                    const content = buf.toString("utf-8");
                    // store in cache
                    FILE_CONTENTS_CACHE.set(filePath, {
                        mtime: st.mtime.getTime(),
                        size: st.size,
                        content,
                    });
                    results.push({ path: filePath, content });
                }
                catch (_b) {
                    // skip
                }
            }
        })));
        // Now remove from cache any file that wasn't encountered.
        const currentKeys = [...FILE_CONTENTS_CACHE.keys()];
        for (const key of currentKeys) {
            if (!seenPaths.has(key)) {
                FILE_CONTENTS_CACHE.delete(key);
            }
        }
        // sort results by path
        results.sort((a, b) => a.path.localeCompare(b.path));
        return results;
    });
}
