import { RuntimeWorkspaceService } from '../../core/runtime/workspaces/index.js';
import { getWorkspaceOperationLogger } from '../../server/logging/workspace-operation-logger.js';
import { createRequestLoggingMiddleware } from './request-logging.js';
export function createWorkspaceRequestLoggingMiddleware(options) {
    return createRequestLoggingMiddleware({
        logger: options.logger,
        resolveLogger: (request) => resolveWorkspaceRequestLogger({ ...options, request }),
    });
}
function resolveWorkspaceRequestLogger(options) {
    try {
        const workspaceContext = RuntimeWorkspaceService.resolveContext({
            workspaceRoot: options.workspaceRoot,
            stateRoot: options.stateRoot,
        });
        const workspaceId = readWorkspaceIdFromRequest(options.request);
        const workspace = workspaceId ?
            workspaceContext.workspaces.find((candidate) => candidate.id === workspaceId)
            : workspaceContext.activeWorkspace;
        return workspace ? getWorkspaceOperationLogger(workspace.stateRoot) : options.logger;
    }
    catch {
        return options.logger;
    }
}
function readWorkspaceIdFromRequest(request) {
    const explicitWorkspaceId = readStringValue(request.query.workspaceId);
    if (explicitWorkspaceId) {
        return explicitWorkspaceId;
    }
    const rawInput = readStringValue(request.query.input);
    if (!rawInput) {
        return undefined;
    }
    try {
        return readWorkspaceIdFromUnknown(JSON.parse(rawInput));
    }
    catch {
        return undefined;
    }
}
function readWorkspaceIdFromUnknown(value) {
    if (!value || typeof value !== 'object') {
        return undefined;
    }
    if (Array.isArray(value)) {
        return value.map(readWorkspaceIdFromUnknown).find(Boolean);
    }
    const record = value;
    const directWorkspaceId = readStringValue(record.workspaceId);
    if (directWorkspaceId) {
        return directWorkspaceId;
    }
    return Object.values(record).map(readWorkspaceIdFromUnknown).find(Boolean);
}
function readStringValue(value) {
    if (typeof value !== 'string') {
        return undefined;
    }
    const trimmed = value.trim();
    return trimmed || undefined;
}
//# sourceMappingURL=workspace-request-logging.js.map