"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SDKTool = void 0;
const logger_1 = require("../../logger/logger");
function toObject(value) {
    if (value && typeof value === "object" && !Array.isArray(value)) {
        return value;
    }
    return {};
}
function normalizeOutput(rawOutput) {
    if (typeof rawOutput !== "string") {
        return rawOutput;
    }
    const trimmed = rawOutput.trim();
    const likelyJson = (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
        (trimmed.startsWith("[") && trimmed.endsWith("]"));
    if (!likelyJson) {
        return rawOutput;
    }
    try {
        return JSON.parse(trimmed);
    }
    catch (_a) {
        return rawOutput;
    }
}
function getErrorMessage(error) {
    var _a;
    if (error instanceof Error) {
        return (_a = error.stack) !== null && _a !== void 0 ? _a : error.message;
    }
    return String(error);
}
class SDKTool {
    constructor(name, rawTool, isInteractive = false) {
        this.name = name;
        this.rawTool = rawTool;
        this.isInteractive = isInteractive;
        this.description = typeof rawTool.description === "string" ? rawTool.description : "";
        this.inputSchema = rawTool.inputSchema;
    }
    async execute(input) {
        const startedAt = Date.now();
        const inputForValidation = typeof input === "undefined" ? {} : input;
        try {
            const parsedInput = this.validateInput(inputForValidation);
            const rawOutput = await this.rawTool.execute(parsedInput);
            const output = normalizeOutput(rawOutput);
            return {
                toolName: this.name,
                success: true,
                input: toObject(parsedInput),
                output,
                rawOutput,
                durationMs: Date.now() - startedAt,
            };
        }
        catch (error) {
            const errorMessage = getErrorMessage(error);
            logger_1.logger.error("SDK tool execution failed", {
                tool_name: this.name,
                error: errorMessage,
            });
            return {
                toolName: this.name,
                success: false,
                input: toObject(inputForValidation),
                output: null,
                rawOutput: null,
                error: errorMessage,
                durationMs: Date.now() - startedAt,
            };
        }
    }
    validateInput(input) {
        const schema = this.rawTool.inputSchema;
        if (schema && typeof schema.parse === "function") {
            return schema.parse(input);
        }
        return input;
    }
}
exports.SDKTool = SDKTool;
