"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const sqlite_1 = require("@aigne/sqlite");
const core_1 = require("@opentelemetry/core");
const drizzle_orm_1 = require("drizzle-orm");
const util_js_1 = require("../../core/util.js");
const migrate_js_1 = require("../../server/migrate.js");
const trace_js_1 = require("../../server/models/trace.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 () => {
                        console.warn("Please setup AIGNEObserver.setExportFn to collect tracing data from agents.");
                    }
                    : this._upsertWithSQLite);
    }
    async _upsertWithSQLite(validatedData) {
        const db = await this._db;
        if (!db)
            throw new Error("Database not initialized");
        for (const trace of validatedData) {
            const whereClause = (0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(trace_js_1.Trace.id, trace.id), (0, drizzle_orm_1.eq)(trace_js_1.Trace.rootId, trace.rootId), !trace.parentId ? (0, drizzle_orm_1.isNull)(trace_js_1.Trace.parentId) : (0, drizzle_orm_1.eq)(trace_js_1.Trace.parentId, trace.parentId));
            try {
                const existing = await db.select().from(trace_js_1.Trace).where(whereClause).limit(1).execute();
                if (existing.length > 0) {
                    await db.update(trace_js_1.Trace).set(trace).where(whereClause).execute();
                }
                else {
                    await db.insert(trace_js_1.Trace).values(trace).execute();
                }
            }
            catch (err) {
                console.error(`upsert spans failed for trace ${trace.id}:`, err);
            }
        }
    }
    async export(spans, resultCallback) {
        try {
            await this.upsert((0, util_js_2.validateTraceSpans)(spans));
            resultCallback({ code: core_1.ExportResultCode.SUCCESS });
        }
        catch (error) {
            console.error("Failed to export spans:", error);
            resultCallback({ code: core_1.ExportResultCode.FAILED });
        }
    }
    shutdown() {
        return Promise.resolve();
    }
    async upsertInitialSpan(span) {
        await this.upsert((0, util_js_2.validateTraceSpans)([span]));
    }
}
exports.default = HttpExporter;
