"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const logger_1 = require("../logger/logger");
const default_1 = require("../sdk/default");
const router = (0, express_1.Router)();
router.post("/ask_stream", async (req, res) => {
    var _a, _b;
    let activeSessionId = "";
    try {
        const { user_query, session_id, metadata } = (_a = req.body) !== null && _a !== void 0 ? _a : {};
        if (typeof user_query !== "string" || typeof session_id !== "string" || !metadata) {
            res.status(400).json({ error: "Invalid request format" });
            return;
        }
        const meta = metadata;
        if (!Array.isArray(meta.accountInfo) || meta.accountInfo.length === 0) {
            res.status(400).json({ error: "Invalid metadata format" });
            return;
        }
        res.setHeader("Content-Type", "text/event-stream");
        res.setHeader("Cache-Control", "no-cache");
        res.setHeader("Connection", "keep-alive");
        const result = await default_1.defaultSdk.ask({
            userQuery: user_query,
            sessionId: session_id,
            metadata: meta,
            onStep: (step) => {
                if (res.writableEnded) {
                    return;
                }
                res.write(`data: ${JSON.stringify({
                    chatId: step.sessionId,
                    response: {
                        type: "step",
                        tool_name: step.toolName,
                        data: step.data,
                        session_id: step.sessionId,
                    },
                })}\n\n`);
            },
        });
        activeSessionId = result.sessionId;
        const finalPayload = {
            type: "finalText",
            data: result.finalText,
            session_id: result.sessionId,
            chain_id: result.chainId,
        };
        if (typeof result.balanceData !== "undefined") {
            finalPayload.balance_data = result.balanceData;
            finalPayload.balance_ui = true;
        }
        res.write(`data: ${JSON.stringify({
            chatId: result.sessionId,
            response: finalPayload,
        })}\n\n`);
        res.write("data: [DONE]\n\n");
        res.end();
    }
    catch (error) {
        const errorMessage = error instanceof Error ? (_b = error.stack) !== null && _b !== void 0 ? _b : error.message : String(error);
        if (activeSessionId) {
            (0, logger_1.createSessionLogger)(activeSessionId).error("Error processing ask_stream", {
                error: errorMessage,
            });
        }
        else {
            logger_1.logger.error("Error processing ask_stream", { error: errorMessage });
        }
        if (!res.writableEnded) {
            res.status(500).json({ error: "Failed to process prompt" });
        }
    }
});
router.get("/stream_history", async (req, res) => {
    const sessionId = typeof req.query.session_id === "string" ? req.query.session_id.trim() : "";
    if (!sessionId) {
        res.status(400).json({ error: "session_id query parameter is required" });
        return;
    }
    try {
        const history = default_1.defaultSdk.getChatHistory(sessionId);
        res.json({ session_id: sessionId, chatHistory: history });
    }
    catch (_a) {
        res.status(404).json({ error: "Chat history not found" });
    }
});
router.get("/sessions/:sessionId/history", (req, res) => {
    var _a;
    const sessionId = (_a = req.params.sessionId) === null || _a === void 0 ? void 0 : _a.trim();
    if (!sessionId) {
        res.status(400).json({ error: "sessionId route parameter is required" });
        return;
    }
    const snapshot = default_1.defaultSdk.getSessionHistory(sessionId);
    if (!snapshot) {
        res.status(404).json({ error: `No logs found for session ${sessionId}` });
        return;
    }
    res.json({
        session_id: snapshot.sessionId,
        summary: snapshot.summary,
        metadata: snapshot.metadata,
        conversation_history: snapshot.conversation,
        logs: snapshot.logs,
    });
});
exports.default = router;
