import { randomUUID } from "node:crypto";
import os from "node:os";
import path from "node:path";
import { findServerAdapter } from "../agent-runtimes/registry.js";
import { unprocessable } from "../errors.js";
import { organizationIntelligenceProfileService, sanitizeConfigForProductIntelligence, } from "./organization-intelligence-profiles.js";
import { executeAdapterWithModelFallbacks } from "./runtime-kernel/model-fallback.js";
import { secretService } from "./secrets.js";
function intelligenceLabel(purpose) {
    return purpose === "lightweight" ? "Fast" : "Smart";
}
function defaultProductIntelligenceCwd() {
    return path.join(os.tmpdir(), "rudder-product-intelligence");
}
function redactRuntimeMeta(meta, secretKeys) {
    if (!meta.env || secretKeys.size === 0)
        return meta;
    const env = { ...meta.env };
    for (const key of secretKeys) {
        if (key in env)
            env[key] = "***REDACTED***";
    }
    return {
        ...meta,
        env,
    };
}
export async function executeResolvedProductIntelligenceProfile(input) {
    const runId = input.runId ?? `product-intelligence-${randomUUID()}`;
    const secretKeys = input.secretKeys ?? new Set();
    const config = {
        ...sanitizeConfigForProductIntelligence(input.config),
        promptTemplate: input.prompt,
    };
    const workspaceCwd = input.workspaceCwd ?? defaultProductIntelligenceCwd();
    const label = intelligenceLabel(input.purpose);
    return executeAdapterWithModelFallbacks(input.adapter, {
        runId,
        agent: {
            id: `product-intelligence-${input.purpose}`,
            orgId: input.orgId,
            name: `${label} Intelligence`,
            agentRuntimeType: input.profile.agentRuntimeType,
            agentRuntimeConfig: config,
        },
        runtime: {
            sessionId: null,
            sessionParams: null,
            sessionDisplayId: null,
            taskKey: null,
        },
        config,
        context: {
            ...(input.context ?? {}),
            rudderScene: "product_intelligence",
            productIntelligence: {
                purpose: input.purpose,
                feature: input.feature,
            },
            rudderWorkspace: {
                source: "product_intelligence",
                strategy: "none",
                cwd: workspaceCwd,
            },
        },
        onLog: input.onLog ?? (async () => { }),
        onMeta: input.onMeta
            ? async (meta) => input.onMeta?.(redactRuntimeMeta(meta, secretKeys))
            : undefined,
        abortSignal: input.abortSignal,
    }, {
        resolveAdapter: input.resolveAdapter,
    });
}
export function productIntelligenceService(db) {
    const profiles = organizationIntelligenceProfileService(db);
    const secrets = secretService(db);
    async function execute(input) {
        const profile = await profiles.getByPurpose(input.orgId, input.purpose);
        const label = intelligenceLabel(input.purpose);
        if (!profile) {
            throw unprocessable(`${label} Intelligence is not configured`);
        }
        if (profile.status === "disabled") {
            throw unprocessable(`${label} Intelligence is disabled`);
        }
        if (profile.status !== "configured") {
            throw unprocessable(`${label} Intelligence is invalid`);
        }
        const adapter = findServerAdapter(profile.agentRuntimeType);
        if (!adapter) {
            throw unprocessable(`${label} Intelligence provider is not available`);
        }
        const { config, secretKeys } = await secrets.resolveAdapterConfigForRuntime(input.orgId, profile.agentRuntimeConfig);
        return executeResolvedProductIntelligenceProfile({
            ...input,
            profile,
            config,
            secretKeys,
            adapter,
            resolveAdapter: findServerAdapter,
        });
    }
    return {
        execute,
    };
}
//# sourceMappingURL=product-intelligence.js.map