"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertTrace = exports.isBlocklet = void 0;
const node_path_1 = __importDefault(require("node:path"));
const decimal_js_1 = __importDefault(require("decimal.js"));
const drizzle_orm_1 = require("drizzle-orm");
const trace_js_1 = require("../server/models/trace.js");
exports.isBlocklet = !!process.env.BLOCKLET_APP_DIR && !!process.env.BLOCKLET_PORT;
const insertTrace = async (db, trace) => {
    if (Number(trace.endTime) > 0) {
        const model = trace.attributes?.output?.model;
        const traces = await db
            .select({
            id: trace_js_1.Trace.id,
            token: trace_js_1.Trace.token,
            cost: trace_js_1.Trace.cost,
        })
            .from(trace_js_1.Trace)
            .where((0, drizzle_orm_1.eq)(trace_js_1.Trace.parentId, trace.id))
            .execute();
        if (traces.length > 0) {
            const tokenDecimal = traces.reduce((acc, curr) => acc.plus(curr.token || 0), new decimal_js_1.default(0));
            trace.token = tokenDecimal.toNumber();
            const costDecimal = traces.reduce((acc, curr) => acc.plus(curr.cost || 0), new decimal_js_1.default(0));
            trace.cost = costDecimal.gt(0) ? Number(costDecimal.toFixed(6)) : 0;
        }
        else {
            const inputTokens = trace.attributes?.output?.usage?.inputTokens || 0;
            const outputTokens = trace.attributes?.output?.usage?.outputTokens || 0;
            trace.token = new decimal_js_1.default(inputTokens).plus(outputTokens).toNumber();
            let price = {};
            try {
                let fullPath = "";
                if (process?.env?.BLOCKLET_APP_DIR) {
                    fullPath = node_path_1.default.resolve(process.env.BLOCKLET_APP_DIR, "dist", "model-prices.json");
                }
                else {
                    fullPath = "../../../dist/model-prices.json";
                }
                // @ts-ignore
                price = await Promise.resolve(`${fullPath}`).then(s => __importStar(require(s)));
            }
            catch {
                price = {};
            }
            if (price && Object.keys(price).length > 0 && model) {
                const value = price[model];
                trace.cost = value
                    ? Number(new decimal_js_1.default(inputTokens)
                        .mul(value.input_cost_per_token || 0)
                        .plus(new decimal_js_1.default(outputTokens).mul(value.output_cost_per_token || 0))
                        .toFixed(6))
                    : 0;
            }
            else {
                trace.cost = 0;
            }
        }
    }
    const insertSql = (0, drizzle_orm_1.sql) `
    INSERT INTO Trace (
      id,
      rootId,
      parentId,
      name,
      startTime,
      endTime,
      attributes,
      status,
      userId,
      sessionId,
      componentId,
      action,
      token,
      cost
    ) VALUES (
      ${trace.id},
      ${trace.rootId},
      ${trace.parentId || null},
      ${trace.name},
      ${trace.startTime},
      ${trace.endTime},
      ${JSON.stringify(trace.attributes)},
      ${JSON.stringify(trace.status)},
      ${trace.userId || null},
      ${trace.sessionId || null},
      ${trace.componentId || null},
      ${trace.action || null},
      ${trace.token || 0},
      ${trace.cost || 0}
    )
    ON CONFLICT(id)
    DO UPDATE SET
      name = excluded.name,
      startTime = excluded.startTime,
      endTime = excluded.endTime,
      attributes = excluded.attributes,
      status = excluded.status,
      userId = excluded.userId,
      sessionId = excluded.sessionId,
      componentId = excluded.componentId,
      action = excluded.action,
      token = excluded.token,
      cost = excluded.cost;
  `;
    await db?.run?.(insertSql);
};
exports.insertTrace = insertTrace;
