"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLIAgent = void 0;
const ai_1 = require("ai");
const ToolFactory_1 = require("../tools/goatTools/ToolFactory");
const ToolNames_1 = require("../tools/goatTools/ToolNames");
const logger_1 = require("../logger/logger");
const dotenv_1 = __importDefault(require("dotenv"));
const openai_1 = require("@ai-sdk/openai");
dotenv_1.default.config();
function parsePositiveInt(value, fallback) {
    const parsed = Number.parseInt(value !== null && value !== void 0 ? value : "", 10);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
function parseNonNegativeInt(value, fallback) {
    const parsed = Number.parseInt(value !== null && value !== void 0 ? value : "", 10);
    return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
}
const MODEL_NAME = (process.env.DZAP_OPENAI_MODEL || "gpt-4o-mini").trim();
const MODEL_MAX_RETRIES = parseNonNegativeInt(process.env.DZAP_MODEL_MAX_RETRIES, 2);
const MODEL_TIMEOUT_MS = parsePositiveInt(process.env.DZAP_MODEL_TIMEOUT_MS, 4500000);
class CLIAgent {
    constructor() {
        this.tools = {};
        this.tools = new ToolFactory_1.ToolFactory().getToolByNames([
            ToolNames_1.ToolNames.PriceTool,
            ToolNames_1.ToolNames.BalanceTool,
            ToolNames_1.ToolNames.TokenAddressTool,
            ToolNames_1.ToolNames.DollarToTokenAmountTool,
            ToolNames_1.ToolNames.TrendingNewsTool,
            ToolNames_1.ToolNames.TrendingTokenTool,
            ToolNames_1.ToolNames.ZapCallDataGeneratorTool,
            ToolNames_1.ToolNames.PerformZapTool,
            ToolNames_1.ToolNames.PricePredictionTool,
            ToolNames_1.ToolNames.SentimentTool,
            ToolNames_1.ToolNames.WebSearchTool,
            ToolNames_1.ToolNames.DefiPositionsTool,
            ToolNames_1.ToolNames.RagOverDocsTool,
            ToolNames_1.ToolNames.PoolTool,
        ]);
        let tool_name_list = [];
        for (let tool_name in this.tools) {
            tool_name_list.push(tool_name.toString());
        }
        logger_1.logger.info("Initialized CLIAgent with tools: " + tool_name_list.join(", "));
    }
    async processPromptStream(messages, system_prompt, onUpdate) {
        logger_1.logger.info("Processing prompt stream");
        try {
            const result = await (0, ai_1.generateText)({
                model: (0, openai_1.openai)(MODEL_NAME),
                tools: this.tools,
                messages: messages,
                system: system_prompt,
                toolChoice: "auto",
                temperature: 0.25,
                maxRetries: MODEL_MAX_RETRIES,
                timeout: { totalMs: MODEL_TIMEOUT_MS },
                stopWhen: (0, ai_1.stepCountIs)(25),
                onStepFinish: (event) => {
                    if (onUpdate) {
                        onUpdate(event);
                    }
                },
            });
            return result.text;
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            logger_1.logger.error("Error processing prompt stream", { message });
            throw new Error(`Failed to generate response: ${message}`);
        }
    }
    async processPrompt(prompt) {
        try {
            const result = await (0, ai_1.generateText)({
                model: (0, openai_1.openai)(MODEL_NAME),
                tools: this.tools,
                prompt: prompt,
                system: "You are a DeFi assistant build by DZap",
                maxRetries: MODEL_MAX_RETRIES,
                timeout: { totalMs: MODEL_TIMEOUT_MS },
                onStepFinish: (event) => {
                    console.log(event.toolResults);
                },
            });
            return result.text;
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            logger_1.logger.error("Error processing prompt", { message });
            throw new Error(`Failed to generate response: ${message}`);
        }
    }
    async getChatHistory(sessionId) {
        return [sessionId];
    }
}
exports.CLIAgent = CLIAgent;
