"use strict";
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.createValidationSourceInventory = createValidationSourceInventory;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const archpilotIgnore_1 = require("./smartInit/archpilotIgnore");
function normalizePath(value) {
    return value.replace(/\\/g, '/');
}
function normalizeAbsolutePath(value) {
    const resolved = path.resolve(value);
    return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
}
function toPosixRelative(workspaceRoot, absolutePath) {
    return normalizePath(path.relative(workspaceRoot, absolutePath));
}
function serializeRequestKey(workspaceRoot, request, includeContentOptions) {
    const rootPath = normalizeAbsolutePath(request.rootPath ?? workspaceRoot);
    const extensions = [...new Set(request.extensions.map((extension) => extension.toLowerCase()))]
        .sort()
        .join(',');
    const ignoredDirectoryNames = [...new Set(request.ignoredDirectoryNames)]
        .sort((left, right) => left.localeCompare(right))
        .join(',');
    return JSON.stringify({
        rootPath,
        extensions,
        ignoredDirectoryNames,
        useArchpilotIgnore: request.useArchpilotIgnore !== false,
        ...(includeContentOptions ? { maxFileSizeBytes: request.maxFileSizeBytes ?? null } : {}),
    });
}
function createValidationSourceInventory(workspaceRoot) {
    const resolvedWorkspaceRoot = path.resolve(workspaceRoot);
    const ignoreMatcher = (0, archpilotIgnore_1.loadArchpilotIgnoreMatcher)(resolvedWorkspaceRoot);
    const fileListCache = new Map();
    const textFileCache = new Map();
    const textCache = new Map();
    const stats = {
        fileListCacheHits: 0,
        fileListCacheMisses: 0,
        textReadCacheHits: 0,
        textReadCacheMisses: 0,
        underlyingTextReads: 0,
        underlyingDirectoryReads: 0,
    };
    const readText = async (filePath, options) => {
        const absolutePath = path.resolve(filePath);
        const key = JSON.stringify({
            path: normalizeAbsolutePath(absolutePath),
            maxFileSizeBytes: options?.maxFileSizeBytes ?? null,
        });
        const cached = textCache.get(key);
        if (cached) {
            stats.textReadCacheHits += 1;
            return cached;
        }
        stats.textReadCacheMisses += 1;
        const readPromise = (async () => {
            try {
                const fileStats = await node_fs_1.promises.stat(absolutePath);
                if (options?.maxFileSizeBytes !== undefined &&
                    fileStats.size > options.maxFileSizeBytes) {
                    return undefined;
                }
                stats.underlyingTextReads += 1;
                return await node_fs_1.promises.readFile(absolutePath, { encoding: 'utf8' });
            }
            catch {
                return undefined;
            }
        })();
        textCache.set(key, readPromise);
        return readPromise;
    };
    const getFilePaths = async (request) => {
        const key = serializeRequestKey(resolvedWorkspaceRoot, request, false);
        const cached = fileListCache.get(key);
        if (cached) {
            stats.fileListCacheHits += 1;
            return cached;
        }
        stats.fileListCacheMisses += 1;
        const scanPromise = (async () => {
            const rootPath = path.resolve(request.rootPath ?? resolvedWorkspaceRoot);
            const allowedExtensions = new Set(request.extensions.map((extension) => extension.toLowerCase()));
            const ignoredDirectoryNames = new Set(request.ignoredDirectoryNames);
            const files = [];
            const stack = [rootPath];
            while (stack.length > 0) {
                const current = stack.pop();
                if (!current) {
                    continue;
                }
                let entries;
                try {
                    stats.underlyingDirectoryReads += 1;
                    entries = await node_fs_1.promises.readdir(current, { withFileTypes: true });
                }
                catch {
                    continue;
                }
                entries.sort((left, right) => left.name.localeCompare(right.name));
                for (const entry of entries) {
                    const absoluteEntryPath = path.join(current, entry.name);
                    const relativeEntryPath = toPosixRelative(resolvedWorkspaceRoot, absoluteEntryPath);
                    if (request.useArchpilotIgnore !== false && ignoreMatcher.isIgnored(relativeEntryPath)) {
                        continue;
                    }
                    if (entry.isDirectory()) {
                        if (entry.name.startsWith('.') || ignoredDirectoryNames.has(entry.name)) {
                            continue;
                        }
                        stack.push(absoluteEntryPath);
                        continue;
                    }
                    if (!entry.isFile()) {
                        continue;
                    }
                    const extension = path.extname(entry.name).toLowerCase();
                    if (allowedExtensions.has(extension)) {
                        files.push(absoluteEntryPath);
                    }
                }
            }
            return files.sort((left, right) => toPosixRelative(resolvedWorkspaceRoot, left).localeCompare(toPosixRelative(resolvedWorkspaceRoot, right)));
        })();
        fileListCache.set(key, scanPromise);
        return scanPromise;
    };
    const getTextFiles = async (request) => {
        const key = serializeRequestKey(resolvedWorkspaceRoot, request, true);
        const cached = textFileCache.get(key);
        if (cached) {
            return cached;
        }
        const filesPromise = (async () => {
            const filePaths = await getFilePaths(request);
            const files = [];
            for (const absolutePath of filePaths) {
                const content = await readText(absolutePath, {
                    maxFileSizeBytes: request.maxFileSizeBytes,
                });
                if (content === undefined) {
                    continue;
                }
                files.push({
                    absolutePath,
                    relativePath: toPosixRelative(resolvedWorkspaceRoot, absolutePath),
                    extension: path.extname(absolutePath).toLowerCase(),
                    content,
                });
            }
            return files;
        })();
        textFileCache.set(key, filesPromise);
        return filesPromise;
    };
    return {
        workspaceRoot: resolvedWorkspaceRoot,
        getFilePaths,
        getTextFiles,
        readText,
        getStats: () => ({ ...stats }),
    };
}
//# sourceMappingURL=validationSourceInventory.js.map