import { globalPerfettoProfiler } from "./perfetto-profiler.js";
/**
 * Default parameter info extraction using heuristics
 */
function defaultExtractParameterInfo(parameters) {
    if (!parameters || typeof parameters !== "object" || parameters === null) {
        return "";
    }
    const params = parameters;
    const info = [];
    // Common parameter names that are useful for display, in priority order
    const commonParams = ["filePath", "fileName", "name", "path", "id", "type"];
    for (const key of commonParams) {
        const value = params[key];
        if (value !== undefined && value !== null) {
            let displayValue = String(value);
            // Truncate long values
            if (displayValue.length > 30) {
                displayValue = displayValue.substring(0, 27) + "...";
            }
            // For path-like fields, show just the basename
            if (key.toLowerCase().includes("path") ||
                key.toLowerCase().includes("file")) {
                const parts = displayValue.split("/");
                displayValue = parts[parts.length - 1] || displayValue;
            }
            info.push(`${key}=${displayValue}`);
            // Limit to 2 parameters to keep names manageable
            if (info.length >= 2)
                break;
        }
    }
    return info.length > 0 ? `:${info.join(",")}` : "";
}
/**
 * Create comprehensive parameter metadata for trace args
 */
function createParameterMetadata(parameters) {
    if (!parameters || typeof parameters !== "object" || parameters === null) {
        return {};
    }
    const params = parameters;
    const metadata = {};
    // Add all parameters with some processing for readability
    for (const [key, value] of Object.entries(params)) {
        if (typeof value === "string") {
            metadata[key] = {
                type: "string",
                length: value.length,
                preview: JSON.stringify(value.slice(0, 10)).slice(1, -1) +
                    (value.length > 10 ? "..." : ""),
            };
        }
        else if (typeof value === "number") {
            metadata[key] = {
                type: "number",
                value,
            };
        }
        else if (typeof value === "boolean") {
            metadata[key] = {
                type: "boolean",
                value,
            };
        }
        else if (Array.isArray(value)) {
            metadata[key] = {
                type: "array",
                length: value.length,
                preview: value
                    .slice(0, 3)
                    .map((item) => typeof item === "string"
                    ? JSON.stringify(item.slice(0, 10)).slice(1, -1) +
                        (item.length > 10 ? "..." : "")
                    : item),
            };
        }
        else if (value && typeof value === "object") {
            metadata[key] = {
                type: "object",
                keys: Object.keys(value),
                preview: JSON.stringify(value).slice(0, 10) + "...",
            };
        }
        else {
            metadata[key] = {
                type: typeof value,
                value: String(value),
            };
        }
    }
    return {
        parameterCount: Object.keys(params).length,
        parameters: metadata,
        toolCallTimestamp: new Date().toISOString(),
    };
}
/**
 * Wraps a tool to add performance profiling
 */
export function profileTool(toolName, tool, config) {
    const originalExecute = tool.execute;
    const profiledTool = {
        ...tool,
        execute: async (parameters, options) => {
            if (!originalExecute) {
                throw new Error(`Tool ${toolName} has no execute function`);
            }
            // Use tool-specific extraction if provided, otherwise use default heuristics
            const paramInfo = config?.extractDisplayName
                ? config.extractDisplayName(parameters)
                : defaultExtractParameterInfo(parameters);
            const paramMetadata = config?.extractMetadata
                ? config.extractMetadata(parameters)
                : createParameterMetadata(parameters);
            // Create or get track for this specific tool
            const trackKey = `tool_${toolName}`;
            const trackName = `Tool: ${toolName}`;
            globalPerfettoProfiler.createTrack(trackKey, trackName, "tool");
            // Use the tool's dedicated track for profiling
            return globalPerfettoProfiler.timeAsync(`${toolName}${paramInfo}`, async () => {
                const result = await originalExecute(parameters, options);
                return result;
            }, trackKey, paramMetadata);
        },
    };
    return profiledTool;
}
/**
 * Profile debug operations
 */
export class DebugProfiler {
    static getTrack() {
        const trackKey = "debug";
        globalPerfettoProfiler.createTrack(trackKey, "Debug Operations", "debug");
        return trackKey;
    }
    /**
     * Profile typecheck operation
     */
    static async profileTypecheck(fn) {
        return globalPerfettoProfiler.timeAsync("typecheck", fn, this.getTrack());
    }
    /**
     * Profile lint operation
     */
    static async profileLint(fn) {
        return globalPerfettoProfiler.timeAsync("lint", fn, this.getTrack());
    }
    /**
     * Profile error collection
     */
    static profileErrorCollection(fn) {
        return globalPerfettoProfiler.timeSync("collect_errors", fn, this.getTrack());
    }
}
//# sourceMappingURL=tool-profiler.js.map