"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const sqlite_1 = require("@aigne/sqlite");
const core_1 = require("@opentelemetry/core");
const util_js_1 = require("../../core/util.js");
const migrate_js_1 = require("../../server/migrate.js");
const image_home_path_js_1 = __importDefault(require("../../server/utils/image-home-path.js"));
const save_files_js_1 = __importDefault(require("../../server/utils/save-files.js"));
const util_js_2 = require("./util.js");
class HttpExporter {
    dbPath;
    _db;
    upsert;
    async getDb() {
        if (util_js_1.isBlocklet)
            return;
        const db = await (0, sqlite_1.initDatabase)({ url: this.dbPath, wal: true });
        await (0, migrate_js_1.migrate)(db);
        return db;
    }
    constructor({ dbPath, exportFn, }) {
        this.dbPath = dbPath;
        this._db ??= this.getDb();
        this.upsert = exportFn ?? (util_js_1.isBlocklet ? async () => { } : this._upsertWithSQLite);
    }
    async _upsertWithSQLite(validatedData) {
        const db = await this._db;
        if (!db)
            throw new Error("Database not initialized");
        for (const trace of validatedData) {
            const dataDir = (0, image_home_path_js_1.default)();
            for (const key of ["files", "images"]) {
                const items = trace.attributes?.output?.[key];
                if (trace?.attributes?.output?.[key] && items?.length) {
                    trace.attributes.output[key] = await (0, save_files_js_1.default)(items, { dataDir });
                }
            }
            await (0, util_js_1.insertTrace)(db, trace);
        }
    }
    async export(spans, resultCallback) {
        try {
            await this.upsert((0, util_js_2.validateTraceSpans)(spans));
            resultCallback({ code: core_1.ExportResultCode.SUCCESS });
        }
        catch (error) {
            console.warn("[Observability] Failed to export spans:", error.cause?.message || error.message);
            resultCallback({ code: core_1.ExportResultCode.FAILED });
        }
    }
    shutdown() {
        return Promise.resolve();
    }
}
exports.default = HttpExporter;
