import { EventEmitter } from "node:events";
import { consola } from "consola";
export class RebuildManager extends EventEmitter {
    _isRunning = false;
    _pendingBuilds = new Map();
    _logger;
    constructor(logger) {
        super();
        this._logger = logger;
    }
    _batchTimer;
    registerBuild(key, title) {
        this._logger.debug(`빌드 등록: ${key} (${title})`);
        let resolver;
        const promise = new Promise((resolve) => {
            resolver = resolve;
        });
        this._pendingBuilds.set(key, { title, promise, resolver });
        if (!this._isRunning) {
            // 워커 스레드들의 buildStart가 도착할 시간을 확보하기 위해 짧은 대기
            if (this._batchTimer != null)
                clearTimeout(this._batchTimer);
            this._batchTimer = setTimeout(() => {
                this._batchTimer = undefined;
                void this._runBatch();
            }, 100);
        }
        return resolver;
    }
    async _runBatch() {
        if (this._isRunning || this._pendingBuilds.size === 0) {
            this._logger.debug(`배치 건너뜀 (running: ${String(this._isRunning)}, pending: ${this._pendingBuilds.size})`);
            return;
        }
        this._isRunning = true;
        const batchBuilds = new Map(this._pendingBuilds);
        this._pendingBuilds.clear();
        const tasks = Array.from(batchBuilds.entries());
        const titles = tasks.map(([, { title }]) => title).join(", ");
        this._logger.start(`리빌드 실행 중... (${titles})`);
        const results = await Promise.allSettled(tasks.map(([, { promise }]) => promise));
        // Defensive: registerBuild의 Promise는 현재 reject되지 않지만,
        // 향후 변경에 대비한 안전장치
        const failed = results.filter((r) => r.status === "rejected");
        if (failed.length > 0) {
            for (const result of failed) {
                this._logger.error(`리빌드 에러 발생: ${String(result.reason)}`);
            }
        }
        this._logger.success(`리빌드 실행 완료 (${titles})`);
        this.emit("batchComplete", Array.from(batchBuilds.keys()));
        this._isRunning = false;
        if (this._pendingBuilds.size > 0) {
            void this._runBatch();
        }
    }
}
//# sourceMappingURL=rebuild-manager.js.map