import fs from 'fs-extra';
import path from 'path';
import { createHash } from 'crypto';

import type ApplicationContainer from '..';
import context from '@server/context';
import type { ChannelInfos } from '../console';
import {
    traceCaptureModes,
    type TTraceCaptureMode,
    type TTraceCall,
    type TTraceCallOrigin,
    type TTraceEvent,
    type TTraceEventType,
    type TTraceSqlQuery,
    type TTraceSqlQueryCallerOrigin,
    type TTraceSqlQueryKind,
    type TTraceSummaryValue,
    type TRequestProfiling,
    type TRequestProfilingApiCall,
    type TRequestProfilingSqlQuery,
    type TRequestTrace,
    type TTraceMemorySnapshot,
    type TRequestTraceListItem,
} from '@common/dev/requestTrace';
import type { TProteumManifest } from '@common/dev/proteumManifest';

export type Config = {
    enable: boolean;
    profilerEnable: boolean;
    requestsLimit: number;
    eventsLimit: number;
    capture: TTraceCaptureMode;
    persistOnError: boolean;
};

type TTraceInspectable = object | PrimitiveValue | bigint | symbol | null | undefined | (() => void);
type TTraceDetails = { [key: string]: TTraceInspectable };
type TSerializeJsonValueOptions = { redactSensitive: boolean };
type TActiveRequestRecord = {
    profiling: TRequestProfiling;
    trace?: TRequestTrace;
    capture?: TTraceCaptureMode;
};

const capturePriority: Record<TTraceCaptureMode, number> = { summary: 0, resolve: 1, deep: 2 };
const sensitiveKeyPattern =
    /(^|\.)(authorization|cookie|set-cookie|password|pass|pwd|secret|token|refreshToken|accessToken|apiKey|apiSecret|secretAccessKey|accessKeyId|privateKey|session|jwt|rawBody)$/i;
const maxStringLength = 240;
const normalizeFilepath = (value: string) => value.replace(/\\/g, '/');
const sqlCommentPattern = /\/\*[\s\S]*?\*\//g;
const sqlLineCommentPattern = /--.*$/gm;
const stackFilepathPatterns = [/\((\/.+?):\d+:\d+\)$/, /at (\/.+?):\d+:\d+$/];

const isTraceCaptureMode = (value: string): value is TTraceCaptureMode =>
    traceCaptureModes.includes(value as TTraceCaptureMode);

const isSensitiveKeyPath = (keyPath: string[]) => sensitiveKeyPattern.test(keyPath.join('.'));

const summarizeString = (value: string) =>
    value.length <= maxStringLength ? value : `${value.slice(0, maxStringLength)}…`;

const serializeJsonValue = (
    value: unknown,
    keyPath: string[],
    seen: WeakSet<object>,
    { redactSensitive }: TSerializeJsonValueOptions,
): unknown => {
    if (redactSensitive && isSensitiveKeyPath(keyPath)) return `[redacted: Sensitive key ${keyPath[keyPath.length - 1] || 'value'}]`;
    if (value === undefined || value === null) return value;
    if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
    if (typeof value === 'bigint') return `${value.toString()}n`;
    if (typeof value === 'symbol') return value.toString();
    if (typeof value === 'function') return `[Function ${value.name || 'anonymous'}]`;

    if (value instanceof Date) return value.toISOString();
    if (value instanceof Error) return { name: value.name, message: value.message, stack: value.stack };
    if (Buffer.isBuffer(value)) return `[Buffer ${value.byteLength} bytes]`;
    if (value instanceof Map)
        return Array.from(value.entries()).map(([entryKey, entryValue], index) =>
            serializeJsonValue([entryKey, entryValue], [...keyPath, `[${index}]`], seen, { redactSensitive }),
        );
    if (value instanceof Set) {
        return Array.from(value.values()).map((entryValue, index) =>
            serializeJsonValue(entryValue, [...keyPath, `[${index}]`], seen, { redactSensitive }),
        );
    }

    if (typeof value !== 'object') return String(value);
    if (seen.has(value)) return `[Circular ${value.constructor?.name || 'Object'}]`;

    seen.add(value);

    if (Array.isArray(value)) {
        return value.map((item, index) => serializeJsonValue(item, [...keyPath, `[${index}]`], seen, { redactSensitive }));
    }

    const serialized: Record<string, unknown> = {};
    for (const [entryKey, entryValue] of Object.entries(value)) {
        const nextValue = serializeJsonValue(entryValue, [...keyPath, entryKey], seen, { redactSensitive });
        if (nextValue !== undefined) serialized[entryKey] = nextValue;
    }

    return serialized;
};

const serializeCaptureValue = (value: TTraceInspectable, key: string) =>
    serializeJsonValue(value, [key], new WeakSet<object>(), { redactSensitive: true });
const serializeRawCaptureValue = (value: TTraceInspectable, key: string) =>
    serializeJsonValue(value, [key], new WeakSet<object>(), { redactSensitive: false });

const summarizeError = (error: Error): TTraceSummaryValue => ({
    kind: 'error',
    name: error.name,
    message: error.message,
    stack: error.stack?.split('\n').slice(0, 5).join('\n'),
});

const summarizeValue = (
    value: TTraceInspectable,
    depth: number,
    seen: WeakSet<object>,
    keyPath: string[],
): TTraceSummaryValue => {
    if (isSensitiveKeyPath(keyPath)) return { kind: 'redacted', reason: `Sensitive key ${keyPath[keyPath.length - 1] || 'value'}` };
    if (value === undefined) return { kind: 'undefined' };
    if (value === null) return null;

    if (typeof value === 'string') return summarizeString(value);
    if (typeof value === 'number' || typeof value === 'boolean') return value;
    if (typeof value === 'bigint') return { kind: 'bigint', value: value.toString() };
    if (typeof value === 'symbol') return { kind: 'symbol', value: value.toString() };
    if (typeof value === 'function') return { kind: 'function', name: value.name || 'anonymous' };

    if (value instanceof Date) return { kind: 'date', value: value.toISOString() };
    if (value instanceof Error) return summarizeError(value);
    if (Buffer.isBuffer(value)) return { kind: 'buffer', byteLength: value.byteLength };
    if (value instanceof Map) return { kind: 'map', size: value.size };
    if (value instanceof Set) return { kind: 'set', size: value.size };

    if (seen.has(value)) {
        return {
            kind: 'object',
            constructorName: value.constructor?.name || 'Object',
            keys: [],
            entries: {},
            truncated: true,
        };
    }

    seen.add(value);

    if (Array.isArray(value)) {
        if (depth <= 0) return { kind: 'array', length: value.length, items: [], truncated: value.length > 0 };

        const items = value
            .slice(0, 10)
            .map((item, index) => summarizeValue(item as TTraceInspectable, depth - 1, seen, [...keyPath, `[${index}]`]));
        return { kind: 'array', length: value.length, items, truncated: value.length > items.length };
    }

    const constructorName = value.constructor?.name || 'Object';
    const keys = Object.keys(value);
    if (depth <= 0) {
        return { kind: 'object', constructorName, keys, entries: {}, truncated: keys.length > 0 };
    }

    const entries: { [key: string]: TTraceSummaryValue } = {};
    for (const key of keys.slice(0, 20)) {
        const record = value as Record<string, TTraceInspectable>;
        entries[key] = summarizeValue(record[key], depth - 1, seen, [...keyPath, key]);
    }

    return { kind: 'object', constructorName, keys, entries, truncated: keys.length > Object.keys(entries).length };
};

const summarizeDetails = (details: TTraceDetails, capture: TTraceCaptureMode) => {
    const depth = capture === 'deep' ? 3 : 1;
    const summarized: { [key: string]: TTraceSummaryValue } = {};

    for (const key of Object.keys(details)) {
        summarized[key] = summarizeValue(details[key], depth, new WeakSet<object>(), [key]);
    }

    return summarized;
};

const summarizeCaptureValue = (value: TTraceInspectable, capture: TTraceCaptureMode, key: string) =>
    summarizeValue(value, capture === 'deep' ? 3 : 1, new WeakSet<object>(), [key]);

const nowIso = () => new Date().toISOString();
const snapshotMemory = (): TTraceMemorySnapshot => {
    const usage = process.memoryUsage();

    return {
        arrayBuffers: typeof usage.arrayBuffers === 'number' ? usage.arrayBuffers : 0,
        external: usage.external,
        heapTotal: usage.heapTotal,
        heapUsed: usage.heapUsed,
        rss: usage.rss,
    };
};

export default class Trace {
    private requests = new Map<string, TActiveRequestRecord>();
    private order: string[] = [];
    private armedCapture?: TTraceCaptureMode;
    private manifestCache?: {
        manifest: TProteumManifest;
        mtimeMs: number;
        serviceByFilepath: Map<string, string>;
    };
    private activeMeasurements = new Map<
        string,
        {
            cpu: ReturnType<typeof process.cpuUsage>;
            memory: TTraceMemorySnapshot;
        }
    >();

    public constructor(
        private container: typeof ApplicationContainer,
        private config: Config,
    ) {}

    public isDevTraceEnabled() {
        return __DEV__ && this.config.enable && this.container.Environment.profile === 'dev';
    }

    public isProfilingEnabled() {
        return this.config.profilerEnable;
    }

    public shouldInstrumentRequests() {
        return this.isDevTraceEnabled() || this.isProfilingEnabled();
    }

    private getContextChannel() {
        return context.getStore() as ChannelInfos | undefined;
    }

    private readManifestCache() {
        const manifestFilepath = path.join(this.container.path.root, '.proteum', 'manifest.json');
        if (!fs.existsSync(manifestFilepath)) return undefined;

        const stats = fs.statSync(manifestFilepath);
        if (this.manifestCache && this.manifestCache.mtimeMs === stats.mtimeMs) return this.manifestCache;

        const manifest = fs.readJSONSync(manifestFilepath) as TProteumManifest;
        const serviceByFilepath = new Map<string, string>();
        for (const service of [...manifest.services.app, ...manifest.services.routerPlugins]) {
            if (!service.sourceFilepath) continue;
            serviceByFilepath.set(normalizeFilepath(path.resolve(service.sourceFilepath)), service.registeredName);
        }

        this.manifestCache = {
            manifest,
            mtimeMs: stats.mtimeMs,
            serviceByFilepath,
        };

        return this.manifestCache;
    }

    private getStackFilepaths(stack?: string) {
        if (!stack) return [];

        const filepaths: string[] = [];
        for (const line of stack.split('\n')) {
            const trimmedLine = line.trim();
            let matchedFilepath: string | undefined;

            for (const pattern of stackFilepathPatterns) {
                const match = trimmedLine.match(pattern);
                if (match?.[1]) {
                    matchedFilepath = match[1];
                    break;
                }
            }

            if (!matchedFilepath) continue;
            if (matchedFilepath.includes('/node_modules/')) continue;

            filepaths.push(normalizeFilepath(path.resolve(matchedFilepath)));
        }

        return filepaths;
    }

    private inferServiceLabelFromStack(stack?: string) {
        const manifestCache = this.readManifestCache();
        if (!manifestCache) return undefined;

        for (const filepath of this.getStackFilepaths(stack)) {
            const serviceLabel = manifestCache.serviceByFilepath.get(filepath);
            if (serviceLabel) return serviceLabel;
        }

        return undefined;
    }

    private normalizeSqlQuery(query: string) {
        return query
            .replace(sqlCommentPattern, ' ')
            .replace(sqlLineCommentPattern, ' ')
            .replace(/'([^']|'')*'/g, '?')
            .replace(/"([^"]|"")*"/g, '?')
            .replace(/\b\d+(?:\.\d+)?\b/g, '?')
            .replace(/\s+/g, ' ')
            .trim()
            .toUpperCase();
    }

    private createSqlFingerprint(query: string) {
        const normalized = this.normalizeSqlQuery(query);

        if (!normalized) return undefined;

        return createHash('sha1').update(normalized).digest('hex').slice(0, 12);
    }

    private createProfiling(input: {
        enabled: boolean;
        id: string;
        method: string;
        path: string;
        url: string;
        profilerOrigin?: string;
        profilerParentRequestId?: string;
    }): TRequestProfiling {
        return {
            enabled: input.enabled,
            requestId: input.id,
            method: input.method,
            path: input.path,
            url: input.url,
            startedAt: nowIso(),
            profilerOrigin: input.profilerOrigin,
            profilerParentRequestId: input.profilerParentRequestId,
            apiCalls: [],
            sqlQueries: [],
        };
    }

    private getRecord(requestId: string) {
        return this.requests.get(requestId);
    }

    public armNextRequest(capture: string) {
        if (!isTraceCaptureMode(capture)) {
            throw new Error(`Unsupported trace capture mode "${capture}". Expected one of: ${traceCaptureModes.join(', ')}.`);
        }

        this.armedCapture = capture;
        return capture;
    }

    public startRequest(input: {
        id: string;
        method: string;
        path: string;
        url: string;
        headers: object;
        data: object;
        profilerSessionId?: string;
        profilerOrigin?: string;
        profilerParentRequestId?: string;
    }) {
        const profilingEnabled = this.shouldInstrumentRequests();
        const profiling = this.createProfiling({
            enabled: profilingEnabled,
            id: input.id,
            method: input.method,
            path: input.path,
            url: input.url,
            profilerOrigin: input.profilerOrigin,
            profilerParentRequestId: input.profilerParentRequestId,
        });
        if (!profilingEnabled) return profiling;

        const traceEnabled = this.isDevTraceEnabled();
        const capture = traceEnabled ? this.armedCapture ?? this.config.capture : undefined;
        this.armedCapture = undefined;

        const trace =
            traceEnabled
                ? ({
                      id: input.id,
                      method: input.method,
                      path: input.path,
                      url: input.url,
                      capture: capture as TTraceCaptureMode,
                      profilerSessionId: input.profilerSessionId,
                      profilerOrigin: input.profilerOrigin,
                      profilerParentRequestId: input.profilerParentRequestId,
                      startedAt: profiling.startedAt,
                      droppedEvents: 0,
                      requestDataJson: serializeCaptureValue(input.data, 'requestData'),
                      calls: [],
                      sqlQueries: [],
                      events: [],
                  } satisfies TRequestTrace)
                : undefined;

        this.requests.set(input.id, {
            profiling,
            trace,
            capture,
        });
        this.activeMeasurements.set(input.id, { cpu: process.cpuUsage(), memory: snapshotMemory() });

        if (trace) {
            this.order.push(input.id);
            this.trimRequestBuffer();
            this.record(input.id, 'request.start', { method: input.method, path: input.path, url: input.url, headers: input.headers, data: input.data });
        }

        return profiling;
    }

    public setRequestUser(requestId: string, user?: string) {
        const record = this.getRecord(requestId);
        if (!record) return;

        record.profiling.user = user;
        if (!record.trace) return;

        const trace = record.trace;
        trace.user = user;
        if (user) this.record(requestId, 'request.user', { user });
    }

    public getCapture(requestId: string) {
        return this.getRecord(requestId)?.capture;
    }

    public shouldCapture(requestId: string, minimumCapture: TTraceCaptureMode) {
        const capture = this.getCapture(requestId);
        if (!capture) return false;

        return capturePriority[capture] >= capturePriority[minimumCapture];
    }

    public record(requestId: string, type: TTraceEventType, details: TTraceDetails, minimumCapture: TTraceCaptureMode = 'summary') {
        const record = this.getRecord(requestId);
        const trace = record?.trace;
        if (!trace || !this.shouldCapture(requestId, minimumCapture)) return;

        if (trace.events.length >= this.config.eventsLimit) {
            trace.droppedEvents++;
            return;
        }

        const event: TTraceEvent = {
            index: trace.events.length,
            at: nowIso(),
            elapsedMs: Math.max(0, Date.now() - Date.parse(trace.startedAt)),
            type,
            details: summarizeDetails(details, trace.capture),
        };

        trace.events.push(event);
    }

    public finishRequest(requestId: string, output: { statusCode: number; user?: string; errorMessage?: string }) {
        const record = this.getRecord(requestId);
        if (!record) return;

        const { profiling, trace } = record;
        if (output.user) profiling.user = output.user;
        profiling.statusCode = output.statusCode;
        profiling.errorMessage = output.errorMessage;

        const measurement = this.activeMeasurements.get(requestId);
        if (measurement) {
            this.activeMeasurements.delete(requestId);

            if (trace) {
                const cpu = process.cpuUsage(measurement.cpu);
                trace.performance = {
                    cpu: {
                        systemMicros: cpu.system,
                        userMicros: cpu.user,
                    },
                    memory: {
                        after: snapshotMemory(),
                        before: measurement.memory,
                    },
                };
            }
        }

        profiling.finishedAt = nowIso();
        profiling.durationMs = Math.max(0, Date.parse(profiling.finishedAt) - Date.parse(profiling.startedAt));

        if (!trace) return;

        if (output.user) trace.user = output.user;
        trace.statusCode = output.statusCode;
        trace.errorMessage = output.errorMessage;
        this.record(
            requestId,
            'request.finish',
            { statusCode: output.statusCode, user: output.user || '', errorMessage: output.errorMessage || '' },
            'summary',
        );

        trace.finishedAt = profiling.finishedAt;
        trace.durationMs = profiling.durationMs;

        if (this.config.persistOnError && trace.statusCode >= 500) {
            trace.persistedFilepath = this.exportRequest(requestId);
        }
    }

    public startCall(
        requestId: string,
        input: {
            origin: TTraceCallOrigin;
            label: string;
            method?: string;
            path?: string;
            fetcherId?: string;
            connectedProjectNamespace?: string;
            connectedControllerAccessor?: string;
            ownerLabel?: string;
            ownerFilepath?: string;
            serviceLabel?: string;
            cacheKey?: string;
            cachePhase?: string;
            parentId?: string;
            requestDataKeys?: string[];
            requestData?: TTraceInspectable;
        },
    ) {
        const record = this.getRecord(requestId);
        if (!record) return undefined;
        const channel = this.getContextChannel();
        const inferredServiceLabel = input.serviceLabel || channel?.serviceLabel || this.inferServiceLabelFromStack(new Error().stack);
        const callIndex = record.profiling.apiCalls.length;
        const startedAt = nowIso();
        const callId = `${requestId}:call:${callIndex}`;

        const profilingCall: TRequestProfilingApiCall = {
            id: callId,
            origin: input.origin,
            label: input.label,
            method: input.method || '',
            path: input.path || '',
            fetcherId: input.fetcherId,
            connectedProjectNamespace: input.connectedProjectNamespace,
            connectedControllerAccessor: input.connectedControllerAccessor,
            ownerLabel: input.ownerLabel || channel?.ownerLabel,
            ownerFilepath: input.ownerFilepath || channel?.ownerFilepath,
            serviceLabel: inferredServiceLabel,
            startedAt,
            requestBodyJson: input.requestData !== undefined ? serializeRawCaptureValue(input.requestData, 'requestData') : undefined,
        };

        record.profiling.apiCalls.push(profilingCall);

        const trace = record.trace;
        if (!trace) return callId;

        const call: TTraceCall = {
            id: callId,
            parentId: input.parentId,
            origin: input.origin,
            label: input.label,
            method: input.method || '',
            path: input.path || '',
            fetcherId: input.fetcherId,
            connectedProjectNamespace: input.connectedProjectNamespace,
            connectedControllerAccessor: input.connectedControllerAccessor,
            ownerLabel: input.ownerLabel || channel?.ownerLabel,
            ownerFilepath: input.ownerFilepath || channel?.ownerFilepath,
            serviceLabel: inferredServiceLabel,
            cacheKey: input.cacheKey || channel?.cacheKey,
            cachePhase: input.cachePhase || channel?.cachePhase,
            startedAt,
            requestDataKeys: input.requestDataKeys || [],
            requestData: input.requestData !== undefined ? summarizeCaptureValue(input.requestData, trace.capture, 'requestData') : undefined,
            requestDataJson: input.requestData !== undefined ? serializeCaptureValue(input.requestData, 'requestData') : undefined,
            resultKeys: [],
        };

        trace.calls.push(call);
        return callId;
    }

    public finishCall(
        requestId: string,
        callId: string | undefined,
        output: {
            statusCode?: number;
            errorMessage?: string;
            resultKeys?: string[];
            result?: TTraceInspectable;
        } = {},
    ) {
        if (!callId) return;

        const record = this.getRecord(requestId);
        const profilingCall = record?.profiling.apiCalls.find((candidate) => candidate.id === callId);
        if (!record || !profilingCall) return;

        profilingCall.finishedAt = nowIso();
        profilingCall.durationMs = Math.max(0, Date.parse(profilingCall.finishedAt) - Date.parse(profilingCall.startedAt));
        profilingCall.statusCode = output.statusCode;
        profilingCall.errorMessage = output.errorMessage;
        profilingCall.responseBodyJson = output.result !== undefined ? serializeRawCaptureValue(output.result, 'result') : undefined;

        const trace = record.trace;
        if (!trace) return;

        const call = trace.calls.find((candidate) => candidate.id === callId);
        if (!call) return;

        call.finishedAt = profilingCall.finishedAt;
        call.durationMs = profilingCall.durationMs;
        call.statusCode = output.statusCode;
        call.errorMessage = output.errorMessage;
        call.resultKeys = output.resultKeys || [];
        call.result = output.result !== undefined ? summarizeCaptureValue(output.result, trace.capture, 'result') : undefined;
        call.resultJson = output.result !== undefined ? serializeCaptureValue(output.result, 'result') : undefined;
    }

    public setRequestResult(requestId: string, result: TTraceInspectable) {
        const trace = this.getRecord(requestId)?.trace;
        if (!trace) return;

        trace.resultJson = serializeCaptureValue(result, 'result');
    }

    public recordSqlQuery(
        requestId: string,
        input: {
            callerCallId?: string;
            callerFetcherId?: string;
            callerLabel?: string;
            callerMethod?: string;
            callerOrigin?: TTraceSqlQueryCallerOrigin;
            callerPath?: string;
            durationMs?: number;
            finishedAt?: string;
            kind: TTraceSqlQueryKind;
            model?: string;
            operation: string;
            ownerLabel?: string;
            ownerFilepath?: string;
            serviceLabel?: string;
            connectedNamespace?: string;
            paramsJson?: unknown;
            paramsText?: string;
            query: string;
            target?: string;
        },
    ) {
        const record = this.getRecord(requestId);
        if (!record) return;
        const channel = this.getContextChannel();

        const durationMs = Math.max(0, input.durationMs || 0);
        const finishedAt = input.finishedAt || nowIso();
        const finishedAtMs = Date.parse(finishedAt);
        const startedAt =
            Number.isFinite(finishedAtMs) && durationMs > 0 ? new Date(finishedAtMs - durationMs).toISOString() : finishedAt;
        const fingerprint = this.createSqlFingerprint(input.query);
        const normalizedQuery = this.normalizeSqlQuery(input.query) || undefined;
        const inferredServiceLabel = input.serviceLabel || channel?.serviceLabel || this.inferServiceLabelFromStack(new Error().stack);

        const profilingQuery: TRequestProfilingSqlQuery = {
            id: `${requestId}:sql:${record.profiling.sqlQueries.length}`,
            callerCallId: input.callerCallId,
            callerFetcherId: input.callerFetcherId,
            callerLabel: input.callerLabel,
            callerMethod: input.callerMethod || '',
            callerOrigin: input.callerOrigin || 'request',
            callerPath: input.callerPath || '',
            durationMs,
            finishedAt,
            kind: input.kind,
            model: input.model,
            operation: input.operation,
            fingerprint,
            normalizedQuery,
            ownerLabel: input.ownerLabel || channel?.ownerLabel,
            ownerFilepath: input.ownerFilepath || channel?.ownerFilepath,
            serviceLabel: inferredServiceLabel,
            connectedNamespace: input.connectedNamespace || channel?.connectedNamespace,
            paramsJson: input.paramsJson,
            paramsText: input.paramsText,
            query: input.query.trim(),
            startedAt,
            target: input.target,
        };

        record.profiling.sqlQueries.push(profilingQuery);
        const trace = record.trace;
        if (!trace) return;

        const sqlQuery: TTraceSqlQuery = {
            id: profilingQuery.id,
            callerCallId: input.callerCallId,
            callerFetcherId: input.callerFetcherId,
            callerLabel: input.callerLabel,
            callerMethod: input.callerMethod || '',
            callerOrigin: input.callerOrigin || 'request',
            callerPath: input.callerPath || '',
            durationMs,
            finishedAt,
            kind: input.kind,
            model: input.model,
            operation: input.operation,
            fingerprint,
            normalizedQuery,
            ownerLabel: input.ownerLabel || channel?.ownerLabel,
            ownerFilepath: input.ownerFilepath || channel?.ownerFilepath,
            serviceLabel: inferredServiceLabel,
            connectedNamespace: input.connectedNamespace || channel?.connectedNamespace,
            paramsJson: input.paramsJson,
            paramsText: input.paramsText,
            query: input.query.trim(),
            startedAt,
            target: input.target,
        };

        trace.sqlQueries.push(sqlQuery);
    }

    public listRequests(limit = 20): TRequestTraceListItem[] {
        return [...this.order]
            .reverse()
            .slice(0, limit)
            .map((requestId) => this.getRecord(requestId)?.trace)
            .filter((trace): trace is TRequestTrace => trace !== undefined)
            .map((trace) => ({
                id: trace.id,
                method: trace.method,
                path: trace.path,
                url: trace.url,
                capture: trace.capture,
                startedAt: trace.startedAt,
                finishedAt: trace.finishedAt,
                durationMs: trace.durationMs,
                statusCode: trace.statusCode,
                user: trace.user,
                droppedEvents: trace.droppedEvents,
                persistedFilepath: trace.persistedFilepath,
                errorMessage: trace.errorMessage,
                profilerSessionId: trace.profilerSessionId,
                profilerOrigin: trace.profilerOrigin,
                profilerParentRequestId: trace.profilerParentRequestId,
                eventCount: trace.events.length,
                callCount: trace.calls.length,
                sqlQueryCount: trace.sqlQueries.length,
            }));
    }

    public listTraceRequests(limit = this.config.requestsLimit) {
        return [...this.order]
            .reverse()
            .slice(0, Math.max(1, limit))
            .map((requestId) => this.getRecord(requestId)?.trace)
            .filter((trace): trace is TRequestTrace => trace !== undefined);
    }

    public getLatestRequest() {
        const latestRequestId = this.order[this.order.length - 1];
        return latestRequestId ? this.getRecord(latestRequestId)?.trace : undefined;
    }

    public getRequest(requestId: string) {
        return this.getRecord(requestId)?.trace;
    }

    public getProfiling(requestId: string) {
        return this.getRecord(requestId)?.profiling;
    }

    public exportRequest(requestId: string, filepath?: string) {
        const trace = this.getRecord(requestId)?.trace;
        if (!trace) throw new Error(`Trace ${requestId} was not found.`);

        const outputFilepath =
            filepath ||
            path.join(this.container.path.var, 'traces', trace.startedAt.slice(0, 10), `${trace.id}.json`);

        fs.ensureDirSync(path.dirname(outputFilepath));
        fs.writeJSONSync(outputFilepath, trace, { spaces: 2 });

        trace.persistedFilepath = outputFilepath;

        return outputFilepath;
    }

    public releaseRequest(requestId: string) {
        const record = this.getRecord(requestId);
        if (!record) return;
        if (record.trace) return;

        this.requests.delete(requestId);
        this.activeMeasurements.delete(requestId);
    }

    private trimRequestBuffer() {
        const overflow = this.order.length - this.config.requestsLimit;
        if (overflow <= 0) return;

        for (const requestId of this.order.splice(0, overflow)) {
            this.requests.delete(requestId);
            this.activeMeasurements.delete(requestId);
        }
    }
}
