import { getSession } from "../lib/neo4j.js";
import { validateCapabilities } from "../lib/validate-capabilities.js";
/**
 * Validate a workflow's step capabilities and update its status.
 * If all steps reference valid plugins with built MCP servers, status → active.
 * Otherwise, status → draft with per-step error messages.
 */
export async function workflowValidate(workflowId, accountId) {
    const platformRoot = process.env.PLATFORM_ROOT;
    if (!platformRoot) {
        throw new Error("PLATFORM_ROOT environment variable is required for validation");
    }
    const session = getSession();
    try {
        // Load workflow + steps
        const result = await session.run(`MATCH (w:Workflow {workflowId: $workflowId, accountId: $accountId})
       OPTIONAL MATCH (w)-[:HAS_STEP]->(s:WorkflowStep)
       RETURN w, collect(s) AS steps`, { workflowId, accountId });
        if (result.records.length === 0) {
            throw new Error(`Workflow not found: ${workflowId}`);
        }
        const record = result.records[0];
        const stepsRaw = record.get("steps");
        if (stepsRaw.length === 0) {
            throw new Error(`Workflow "${workflowId}" has no steps`);
        }
        const steps = stepsRaw.map((s) => ({
            stepId: s.properties.stepId,
            type: s.properties.type,
            plugin: s.properties.plugin,
            tool: s.properties.tool,
            position: s.properties.position ?? 0,
            label: s.properties.label,
        }));
        const validation = validateCapabilities(steps, platformRoot);
        const newStatus = validation.valid ? "active" : "draft";
        const errors = validation.errors.map((e) => `Step "${e.label}": ${e.reason}`);
        // Update workflow status
        const now = new Date().toISOString();
        await session.run(`MATCH (w:Workflow {workflowId: $workflowId, accountId: $accountId})
       SET w.status = $status, w.updatedAt = $now`, { workflowId, accountId, status: newStatus, now });
        return {
            workflowId,
            valid: validation.valid,
            status: newStatus,
            errors,
        };
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=workflow-validate.js.map