import fs from "fs-extra";
import * as path from "path";
import { measureLatency } from "../../optimization/latency-optimizer.js";
import { getWorkspaceIsolation } from "../../workspace/workspace-isolation.js";
/**
 * Unified Virtual File System Router
 * Centralizes all file operations to prevent "Split Brain" scenarios and enable
 * virtual file systems (e.g. for testing, archives, or remote sync).
 */
export class UnifiedVfsRouter {
    static instance;
    providers = new Map();
    constructor() { }
    static get Instance() {
        if (!UnifiedVfsRouter.instance) {
            UnifiedVfsRouter.instance = new UnifiedVfsRouter();
        }
        return UnifiedVfsRouter.instance;
    }
    /**
     * Default implementation using physical file system (fs-extra)
     * File operations are wrapped with latency measurement for performance tracking.
     */
    async readFile(filePath, encoding = "utf-8") {
        return measureLatency('file_read', () => fs.readFile(filePath, encoding));
    }
    async readFileBuffer(filePath) {
        return measureLatency('file_read_buffer', () => fs.readFile(filePath));
    }
    async writeFile(filePath, content, encoding = "utf-8") {
        await measureLatency('file_write', () => fs.writeFile(filePath, content, encoding));
    }
    async writeFileBuffer(filePath, content) {
        await measureLatency('file_write_buffer', () => fs.writeFile(filePath, content));
    }
    async exists(filePath) {
        return fs.pathExists(filePath);
    }
    async stat(filePath) {
        return fs.stat(filePath);
    }
    async readdir(dirPath) {
        return fs.readdir(dirPath);
    }
    async readDirectory(dirPath) {
        const entries = await fs.readdir(dirPath, { withFileTypes: true });
        return entries.map(entry => ({
            name: entry.name,
            isDirectory: entry.isDirectory(),
            isFile: entry.isFile()
        }));
    }
    async ensureDir(dirPath) {
        return fs.ensureDir(dirPath);
    }
    async remove(filePath) {
        return fs.remove(filePath);
    }
    async rename(oldPath, newPath) {
        return fs.rename(oldPath, newPath);
    }
    /**
     * Validates path traversal prevention using workspace isolation.
     * Delegates to WorkspaceIsolation for comprehensive security checks:
     * - Workspace boundary validation
     * - Path traversal prevention
     * - Symlink escape detection
     * - Blocked path enforcement
     * - System whitelist support
     */
    resolvePath(filePath, baseDir) {
        const isolation = getWorkspaceIsolation();
        // If isolation is disabled or baseDir differs from workspace root,
        // fall back to basic path validation
        if (!isolation.getConfig().enabled) {
            return this.basicResolvePath(filePath, baseDir);
        }
        // Use workspace isolation for comprehensive validation
        const result = isolation.validatePath(filePath, 'vfs_resolve');
        return {
            valid: result.valid,
            resolved: result.resolved,
            error: result.error,
        };
    }
    /**
     * Basic path resolution without workspace isolation.
     * Used as fallback when isolation is disabled.
     */
    basicResolvePath(filePath, baseDir) {
        const resolved = path.resolve(filePath);
        const normalizedBase = path.normalize(baseDir);
        const normalizedResolved = path.normalize(resolved);
        // First check: normalized path must be within base directory
        if (!normalizedResolved.startsWith(normalizedBase + path.sep) &&
            normalizedResolved !== normalizedBase) {
            return {
                valid: false,
                resolved,
                error: `Path traversal not allowed: ${filePath} resolves outside project directory`
            };
        }
        // Second check: if file exists, resolve symlinks and verify real path
        // Note: We use fs directly here because realpath is a physical FS concept
        try {
            if (fs.existsSync(resolved)) {
                const realPath = fs.realpathSync(resolved);
                const realBase = fs.realpathSync(baseDir);
                if (!realPath.startsWith(realBase + path.sep) && realPath !== realBase) {
                    return {
                        valid: false,
                        resolved,
                        error: `Symlink traversal not allowed: ${filePath} points outside project directory`
                    };
                }
            }
        }
        catch (_err) {
            // If realpath fails, allow the operation (file may not exist yet)
        }
        return { valid: true, resolved };
    }
    /**
     * Validate a path using workspace isolation
     * Returns the full PathValidationResult for detailed error handling
     */
    validateWithIsolation(filePath, operation) {
        return getWorkspaceIsolation().validatePath(filePath, operation);
    }
}
//# sourceMappingURL=unified-vfs-router.js.map