"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.metadata = void 0;
const db_1 = require("@b/db");
const utils_1 = require("../../utils");
const query_1 = require("@b/utils/query");
const error_1 = require("@b/utils/error");
const queries_1 = require("../../utils/scylla/queries");
const console_1 = require("@b/utils/console");
exports.metadata = {
    summary: "List all bots for a specific AI Market Maker",
    operationId: "listMarketMakerBots",
    tags: ["Admin", "AI Market Maker", "Bot"],
    description: "Retrieves all AI bots associated with a specific market maker, including their configuration, status, and trading statistics. Returns enhanced bot data with trade metrics from both MySQL (dailyTradeCount) and Scylla (actual trade records).",
    parameters: [
        {
            index: 0,
            name: "marketId",
            in: "path",
            required: true,
            description: "ID of the AI Market Maker",
            schema: { type: "string" },
        },
    ],
    responses: {
        200: {
            description: "List of bots with configuration, status, and trading statistics",
            content: {
                "application/json": {
                    schema: {
                        type: "array",
                        items: {
                            type: "object",
                            properties: {
                                ...utils_1.aiBotSchema,
                                tradesExecuted: {
                                    type: "number",
                                    description: "Total number of trades executed by the bot",
                                },
                                profitableTrades: {
                                    type: "number",
                                    description: "Number of profitable trades",
                                },
                                totalVolume: {
                                    type: "number",
                                    description: "Total trading volume generated by the bot",
                                },
                                totalPnL: {
                                    type: "number",
                                    description: "Total profit/loss (always 0 for AI-to-AI trades)",
                                },
                                botType: {
                                    type: "string",
                                    description: "Bot personality type (SCALPER, SWING, ACCUMULATOR, DISTRIBUTOR, MARKET_MAKER)",
                                },
                                stats: {
                                    type: "object",
                                    description: "Detailed trading statistics for the bot",
                                    properties: {
                                        totalTrades: {
                                            type: "number",
                                            description: "Total number of trades",
                                        },
                                        successRate: {
                                            type: "number",
                                            description: "Success rate (0.5 = 50%)",
                                        },
                                        avgProfitPerTrade: {
                                            type: "number",
                                            description: "Average profit per trade",
                                        },
                                        isActive: {
                                            type: "boolean",
                                            description: "Whether the bot is currently active",
                                        },
                                        timeSinceLastTrade: {
                                            type: "number",
                                            nullable: true,
                                            description: "Milliseconds since last trade, or null if never traded",
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
        401: query_1.unauthorizedResponse,
        404: (0, query_1.notFoundMetadataResponse)("AI Market Maker"),
        500: query_1.serverErrorResponse,
    },
    requiresAuth: true,
    logModule: "ADMIN_AI",
    logTitle: "Get Market Maker Bots",
    permission: "view.ai.market-maker.bot",
};
exports.default = async (data) => {
    const { params, ctx } = data;
    ctx === null || ctx === void 0 ? void 0 : ctx.step("Get Market Maker Bots");
    const marketMaker = await db_1.models.aiMarketMaker.findByPk(params.marketId);
    if (!marketMaker) {
        throw (0, error_1.createError)(404, "AI Market Maker not found");
    }
    const bots = await db_1.models.aiBot.findAll({
        where: { marketMakerId: params.marketId },
        order: [["personality", "ASC"]],
    });
    // Get trade stats from Scylla for all bots
    // IMPORTANT: Use marketMaker.marketId (ecosystemMarket.id), NOT params.marketId (aiMarketMaker.id)
    // Trades are stored in Scylla using ecosystemMarket.id as the market_id
    const marketMakerAny = marketMaker;
    const ecosystemMarketId = marketMakerAny.marketId;
    console_1.logger.info("AI_MM", `Querying Scylla with ecosystemMarket.id: ${ecosystemMarketId}`);
    console_1.logger.info("AI_MM", `aiMarketMaker.id (params.marketId): ${params.marketId}`);
    console_1.logger.debug("AI_MM", "MySQL bots", bots.map((b) => ({ id: b.id, name: b.name })));
    // Debug: Get ALL trades to verify data exists
    const allTrades = await (0, queries_1.debugGetAllTrades)(10);
    console_1.logger.debug("AI_MM", `Found ${allTrades.length} total trades in Scylla`);
    if (allTrades.length > 0) {
        console_1.logger.debug("AI_MM", `First trade market_id: ${allTrades[0].marketId}`);
        console_1.logger.debug("AI_MM", `First trade buyBotId: ${allTrades[0].buyBotId}`);
        console_1.logger.debug("AI_MM", `First trade sellBotId: ${allTrades[0].sellBotId}`);
    }
    const botTradeStats = await (0, queries_1.getBotTradeStats)(ecosystemMarketId);
    console_1.logger.debug("AI_MM", `Got ${botTradeStats.size} bot stats entries from Scylla`);
    if (botTradeStats.size > 0) {
        console_1.logger.debug("AI_MM", "Bot stats keys", Array.from(botTradeStats.keys()));
    }
    // Log MySQL dailyTradeCount values
    console_1.logger.debug("AI_MM", "MySQL dailyTradeCounts", bots.map((b) => ({ id: b.id, name: b.name, dailyTradeCount: b.dailyTradeCount })));
    // Enhance bots with stats from both MySQL (dailyTradeCount) and Scylla (actual trades)
    ctx === null || ctx === void 0 ? void 0 : ctx.success("Get Market Maker Bots retrieved successfully");
    return bots.map((bot) => {
        const scyllaStats = botTradeStats.get(bot.id) || { tradeCount: 0, totalVolume: 0 };
        // Use the higher of MySQL dailyTradeCount or Scylla trade count
        // (Scylla has the actual trades, MySQL tracks in-memory count that persists to DB)
        const totalTrades = Math.max(bot.dailyTradeCount || 0, scyllaStats.tradeCount);
        console_1.logger.debug("AI_MM", `Bot ${bot.name}: MySQL=${bot.dailyTradeCount || 0}, Scylla=${scyllaStats.tradeCount}, using=${totalTrades}`);
        return {
            ...bot.toJSON(),
            // Fields expected by frontend
            botType: bot.personality, // Frontend uses botType, DB has personality
            tradesExecuted: totalTrades,
            profitableTrades: Math.floor(totalTrades * 0.5), // 50% profitable (AI trades are neutral)
            totalVolume: scyllaStats.totalVolume,
            totalPnL: 0, // AI-to-AI trades are zero-sum within the system
            stats: {
                totalTrades,
                successRate: 0.5, // AI trades are balanced by design
                avgProfitPerTrade: 0,
                isActive: bot.status === "ACTIVE",
                timeSinceLastTrade: bot.lastTradeAt
                    ? Date.now() - new Date(bot.lastTradeAt).getTime()
                    : null,
            },
        };
    });
};
