import { toErrorMessage } from '../utils/error.js';
import { getRootLogger } from '../utils/logger.js';
export class BaseExecutionContext {
    log;
    ready = false;
    listeners = [];
    constructor() {
        this.log = getRootLogger().child({ component: this.constructor.name });
    }
    async initialize() {
        try {
            await this.doInitialize();
            this.ready = true;
            this.emit({ type: 'context_initialized', contextId: this.id, environment: this.environment });
            this.emit({ type: 'context_ready', contextId: this.id });
            this.log.info(`Execution context initialized: ${this.id} (${this.environment})`);
        }
        catch (err) {
            const message = toErrorMessage(err);
            this.emit({ type: 'context_error', contextId: this.id, error: message });
            this.log.error(`Execution context initialization failed: ${this.id}`, { error: message });
            throw err;
        }
    }
    isReady() {
        return this.ready;
    }
    async teardown() {
        try {
            await this.doTeardown();
        }
        finally {
            this.ready = false;
            this.emit({ type: 'context_teardown', contextId: this.id });
            this.log.info(`Execution context torn down: ${this.id}`);
        }
    }
    on(listener) {
        this.listeners.push(listener);
    }
    off(listener) {
        const index = this.listeners.indexOf(listener);
        if (index >= 0)
            this.listeners.splice(index, 1);
    }
    emit(event) {
        for (const listener of this.listeners) {
            try {
                listener(event);
            }
            catch (err) {
                this.log.error('Execution context event listener error', {
                    error: toErrorMessage(err),
                });
            }
        }
    }
}
//# sourceMappingURL=base.js.map