// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only
import path from 'node:path';
import { readFile } from 'node:fs/promises';
import YAML from 'yaml';
import { getErrorMessage } from '@lumenflow/core/error-handler';
import { CONFIG_FILES } from '@lumenflow/core/wu-constants';
import { WU_LIFECYCLE_SYNC_CONFIG, WU_LIFECYCLE_SYNC_LOG_PREFIX, WU_LIFECYCLE_SYNC_RESULT_DEFAULTS, WU_LIFECYCLE_SYNC_SKIPPED_REASONS, } from './constants.js';
import { createNoopSink } from './noop-sink.js';
function isRecord(value) {
    return typeof value === 'object' && value !== null;
}
function asNonEmptyString(value) {
    if (typeof value !== 'string') {
        return undefined;
    }
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : undefined;
}
function createNoopSyncResult(skippedReason) {
    return {
        sent: WU_LIFECYCLE_SYNC_RESULT_DEFAULTS.SENT,
        accepted: WU_LIFECYCLE_SYNC_RESULT_DEFAULTS.ACCEPTED,
        skippedReason,
    };
}
function createParseInput(workspaceId, controlPlaneRaw) {
    return {
        [WU_LIFECYCLE_SYNC_CONFIG.WORKSPACE_ID_FIELD]: workspaceId,
        [WU_LIFECYCLE_SYNC_CONFIG.CONTROL_PLANE_FIELD]: controlPlaneRaw,
    };
}
async function loadControlPlaneSdk(logger) {
    try {
        return await import('@lumenflow/control-plane-sdk');
    }
    catch (error) {
        logger?.warn?.(`${WU_LIFECYCLE_SYNC_LOG_PREFIX} control-plane SDK unavailable: ${getErrorMessage(error)}`);
        return null;
    }
}
export async function resolveWuLifecycleEventSink(options = {}) {
    const workspaceRoot = options.workspaceRoot ?? process.cwd();
    const workspacePath = path.join(workspaceRoot, CONFIG_FILES.WORKSPACE_CONFIG);
    let workspaceContent;
    try {
        workspaceContent = await readFile(workspacePath, WU_LIFECYCLE_SYNC_CONFIG.TEXT_ENCODING_UTF8);
    }
    catch {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.WORKSPACE_CONFIG_MISSING);
    }
    let parsedWorkspace;
    try {
        parsedWorkspace = YAML.parse(workspaceContent);
    }
    catch {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.WORKSPACE_CONFIG_INVALID);
    }
    if (!isRecord(parsedWorkspace)) {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.WORKSPACE_CONFIG_INVALID);
    }
    const workspaceId = asNonEmptyString(Reflect.get(parsedWorkspace, WU_LIFECYCLE_SYNC_CONFIG.WORKSPACE_ID_FIELD));
    if (!workspaceId) {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.WORKSPACE_ID_MISSING);
    }
    const controlPlaneRaw = Reflect.get(parsedWorkspace, WU_LIFECYCLE_SYNC_CONFIG.CONTROL_PLANE_FIELD);
    if (!isRecord(controlPlaneRaw)) {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.CONTROL_PLANE_NOT_CONFIGURED);
    }
    const controlPlaneSdk = await loadControlPlaneSdk(options.logger);
    if (!controlPlaneSdk) {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.CONTROL_PLANE_SDK_UNAVAILABLE);
    }
    const { parseWorkspaceControlPlaneConfig, createHttpControlPlaneSyncPort } = controlPlaneSdk;
    let runtimeConfig;
    try {
        runtimeConfig = parseWorkspaceControlPlaneConfig(createParseInput(workspaceId, controlPlaneRaw));
    }
    catch {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.CONTROL_PLANE_INVALID);
    }
    const environment = options.environment ?? process.env;
    const tokenEnv = runtimeConfig.control_plane.auth.token_env;
    const token = asNonEmptyString(environment[tokenEnv]);
    if (!token) {
        return createNoopSink(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.MISSING_TOKEN_ENV);
    }
    const syncPort = createHttpControlPlaneSyncPort(runtimeConfig.control_plane, options.logger, {
        fetchFn: options.fetchFn,
        environment,
        timeoutMs: options.timeoutMs,
    });
    return {
        async push(events) {
            if (events.length === 0) {
                return createNoopSyncResult(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.NO_EVENTS);
            }
            try {
                const result = await syncPort.pushKernelEvents({
                    workspace_id: workspaceId,
                    events,
                });
                return {
                    sent: result.accepted > 0,
                    accepted: result.accepted,
                    ...(result.accepted > 0
                        ? {}
                        : {
                            skippedReason: WU_LIFECYCLE_SYNC_SKIPPED_REASONS.NO_EVENTS_ACCEPTED,
                        }),
                };
            }
            catch (error) {
                options.logger?.warn?.(`${WU_LIFECYCLE_SYNC_LOG_PREFIX} pushKernelEvents failed: ${getErrorMessage(error)}`);
                return createNoopSyncResult(WU_LIFECYCLE_SYNC_SKIPPED_REASONS.PUSH_FAILED);
            }
        },
    };
}
//# sourceMappingURL=control-plane-sink.js.map