import { getWorkflowStepKind } from '../../../core/models/workflow-step-kind.js';
import { getWorkflowTrustInfo } from './workflowTrustSource.js';
function hasPrivilegedRuntimePrepare(workflow) {
    return (workflow.runtime?.prepare?.length ?? 0) > 0;
}
function findPrivilegedAllowGitCommitStep(steps) {
    for (const step of steps) {
        if (step.allowGitCommit === true) {
            return step;
        }
        const privilegedParallelStep = step.parallel
            ? findPrivilegedAllowGitCommitStep(step.parallel)
            : undefined;
        if (privilegedParallelStep) {
            return privilegedParallelStep;
        }
    }
    return undefined;
}
function findPrivilegedCapability(steps) {
    const privilegedSystemStep = findPrivilegedSystemStep(steps);
    if (privilegedSystemStep) {
        return { step: privilegedSystemStep, reason: 'system' };
    }
    const privilegedAllowGitCommitStep = findPrivilegedAllowGitCommitStep(steps);
    if (privilegedAllowGitCommitStep) {
        return { step: privilegedAllowGitCommitStep, reason: 'allow_git_commit' };
    }
    return undefined;
}
function findPrivilegedSystemStep(steps) {
    return steps.find((step) => getWorkflowStepKind(step) === 'system');
}
export function validateWorkflowCallTrustBoundary(parentTrustInfo, childWorkflow, stepName, projectCwd) {
    const childTrustInfo = getWorkflowTrustInfo(childWorkflow, projectCwd);
    const privilegedCapability = findPrivilegedCapability(childWorkflow.steps);
    const hasPrivilegedRuntime = hasPrivilegedRuntimePrepare(childWorkflow);
    if (!privilegedCapability && !hasPrivilegedRuntime) {
        return;
    }
    if (parentTrustInfo.isProjectWorkflowRoot && childTrustInfo.isProjectWorkflowRoot) {
        return;
    }
    throw new Error(`Workflow step "${stepName}" cannot call privileged workflow "${childWorkflow.name}" across trust boundary`);
}
//# sourceMappingURL=workflowTrustBoundary.js.map