"use strict";
/**
 * Persistence activities for the workflow planner.
 * These are side-effect functions that update the database.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.persistPlan = persistPlan;
exports.persistBuiltWorkflow = persistBuiltWorkflow;
exports.updateSetStatus = updateSetStatus;
exports.deploySetNamespaces = deploySetNamespaces;
const workflow_sets_1 = require("../../../../services/workflow-sets");
const db_1 = require("../../../../services/yaml-workflow/db");
const deployer_1 = require("../../../../services/yaml-workflow/deployer");
const workers_1 = require("../../../../services/yaml-workflow/workers");
async function persistPlan(setId, planItems, namespaces) {
    const ns = namespaces || [...new Set(planItems.map(w => w.namespace))];
    await (0, workflow_sets_1.updateWorkflowSetPlan)(setId, planItems, ns);
}
async function persistBuiltWorkflow(setId, planItem, builderOutput) {
    const input = {
        name: builderOutput.name,
        description: builderOutput.description,
        app_id: planItem.namespace,
        yaml_content: builderOutput.yaml_content,
        graph_topic: builderOutput.graph_topic || builderOutput.name,
        input_schema: builderOutput.input_schema,
        output_schema: builderOutput.output_schema,
        activity_manifest: builderOutput.activity_manifest,
        tags: builderOutput.tags || [],
        source_workflow_type: 'mcpWorkflowPlanner',
        original_prompt: builderOutput.original_prompt,
        set_id: setId,
        set_role: planItem.role,
        set_build_order: planItem.build_order,
    };
    const record = await (0, db_1.createYamlWorkflow)(input);
    return record.id;
}
async function updateSetStatus(setId, status) {
    await (0, workflow_sets_1.updateWorkflowSetStatus)(setId, status);
}
async function deploySetNamespaces(namespaces) {
    for (const namespace of namespaces) {
        await (0, deployer_1.deployAppId)(namespace, '1');
        // Register workers and activate all workflows in this namespace
        const siblings = await (0, db_1.listYamlWorkflowsByAppId)(namespace);
        for (const sibling of siblings) {
            await (0, db_1.updateYamlWorkflowVersion)(sibling.id, '1');
            await (0, workers_1.registerWorkersForWorkflow)(sibling);
            if (sibling.status === 'draft' || sibling.status === 'deployed') {
                await (0, db_1.updateYamlWorkflowStatus)(sibling.id, 'active');
            }
        }
        await (0, db_1.markAppIdContentDeployed)(namespace);
    }
}
