"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIGNEObserver = void 0;
const api_1 = require("@opentelemetry/api");
const archive_config_js_1 = require("../core/archive-config.js");
const archive_scheduler_js_1 = require("../core/archive-scheduler.js");
const db_path_js_1 = __importDefault(require("../core/db-path.js"));
const type_js_1 = require("../core/type.js");
const util_js_1 = require("../core/util.js");
const init_js_1 = require("../opentelemetry/instrument/init.js");
class AIGNEObserver {
    storage;
    retentionConfig;
    tracer = api_1.trace.getTracer("aigne-tracer");
    processor;
    exporter;
    sdkServerStarted;
    archiveScheduler;
    sdk;
    static exportFn;
    static setExportFn(exportFn) {
        AIGNEObserver.exportFn = exportFn;
    }
    static updateFn;
    static setUpdateFn(updateFn) {
        AIGNEObserver.updateFn = updateFn;
    }
    constructor(options) {
        const parsed = type_js_1.AIGNEObserverOptionsSchema.parse(options);
        this.storage = parsed?.storage ?? (!util_js_1.isBlocklet ? (0, db_path_js_1.default)() : undefined);
        this.retentionConfig = parsed?.retention;
    }
    async serve() {
        this.sdkServerStarted ??= this._serve();
        return this.sdkServerStarted;
    }
    async _serve() {
        if (!this.storage && !util_js_1.isBlocklet) {
            throw new Error("Server storage is not configured");
        }
        const { sdk, spanProcessor, traceExporter } = await (0, init_js_1.initOpenTelemetry)({
            dbPath: this.storage,
            exportFn: AIGNEObserver.exportFn,
            updateFn: AIGNEObserver.updateFn,
        });
        this.sdk = sdk;
        this.processor = spanProcessor;
        this.exporter = traceExporter;
        // Initialize and start archive scheduler if retention config provided
        if (this.storage && this.retentionConfig) {
            try {
                const validatedConfig = (0, archive_config_js_1.validateRetentionConfig)(this.retentionConfig);
                this.archiveScheduler = new archive_scheduler_js_1.ArchiveScheduler(this.storage, validatedConfig);
                this.archiveScheduler.start();
                console.log("[Observability] Archive scheduler started");
            }
            catch (error) {
                console.error("[Observability] Failed to start archive scheduler:", error);
            }
        }
    }
    async flush(span) {
        await this.processor?.onEnd(span);
        await this.processor?.forceFlush();
    }
    async update(id, data) {
        await this.exporter?.update(id, data);
    }
    async close(contextIds = []) {
        try {
            // Stop archive scheduler
            if (this.archiveScheduler) {
                this.archiveScheduler.stop();
                this.archiveScheduler = undefined;
                console.log("[Observability] Archive scheduler stopped");
            }
            await this.exporter?.shutdown(contextIds);
            this.processor = undefined;
            this.sdk = undefined;
            this.sdkServerStarted = undefined;
        }
        catch (error) {
            console.error("[Observability] Error during shutdown:", error);
        }
    }
}
exports.AIGNEObserver = AIGNEObserver;
