"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 api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const fastq_1 = __importDefault(require("fastq"));
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;
    _update;
    updateQueue;
    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, updateFn, }) {
        this.dbPath = dbPath;
        this._db ??= this.getDb();
        this.upsert = exportFn ?? (util_js_1.isBlocklet ? async () => { } : this._upsertWithSQLite);
        this._update = updateFn ?? (util_js_1.isBlocklet ? async () => { } : this._updateWithSQLite);
        this.updateQueue = fastq_1.default.promise(this.updateWorker.bind(this), 1);
    }
    async updateWorker(task) {
        await this._update(task.id, task.data);
    }
    update = (id, data) => {
        return this.updateQueue.push({ id, data });
    };
    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 _updateWithSQLite(id, data) {
        const db = await this._db;
        if (!db)
            throw new Error("Database not initialized");
        await (0, util_js_1.updateTrace)(db, id, data);
    }
    async export(spans, resultCallback) {
        try {
            const data = (0, util_js_2.validateTraceSpans)(spans);
            await this.upsert(data);
            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 });
        }
    }
    async shutdown(contextIds = []) {
        await this.updateQueue.drained();
        if (this._db) {
            const db = await this._db;
            await (0, util_js_1.updateStatusByIds)(db, contextIds, { code: api_1.SpanStatusCode.ERROR, message: "Exited" });
        }
    }
}
exports.default = HttpExporter;
