"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasReflectableCompletedControllerChild = hasReflectableCompletedControllerChild;
exports.areOpenBlockersOnlyUnresolvedMaterializedControllerChildren = areOpenBlockersOnlyUnresolvedMaterializedControllerChildren;
const plan_progress_1 = require("../../workflows/plan-progress");
const workflow_structure_1 = require("../workflow-structure");
const shared_1 = require("./spawn-child-controller/shared");
async function hasReflectableCompletedControllerChild(input) {
    const candidates = selectClosedUnreflectedReadyControllerChildBlockers(input);
    if (candidates.length === 0) {
        return false;
    }
    const workflowStateByIssueId = await (0, shared_1.loadControllerChildCanonicalStateMap)({
        ticketTracker: input.ticketTracker,
        issues: candidates.map((candidate) => candidate.blocker),
    });
    return candidates.some((candidate) => {
        const childWorkflowState = workflowStateByIssueId.get(candidate.blocker.id) ?? null;
        return ((0, shared_1.isControllerChildForParent)({
            workflowState: childWorkflowState,
            parentDisplayId: input.parentIssue.displayId,
            childKey: candidate.childKey,
        }) &&
            (0, plan_progress_1.isClosedCompletedControllerChildIssue)({
                issue: candidate.blocker,
                workflowState: childWorkflowState,
            }));
    });
}
function selectClosedUnreflectedReadyControllerChildBlockers(input) {
    const blockerById = new Map(input.blockers.map((blocker) => [blocker.id, blocker]));
    return (0, shared_1.selectReadyControllerChildIssueSteps)(input.workflowState).flatMap((step) => {
        const childIssueId = (0, shared_1.normalizeControllerChildIssueRef)(step.childIssueRef);
        if (childIssueId === null) {
            return [];
        }
        const blocker = blockerById.get(childIssueId);
        if (blocker === undefined || blocker.isOpen) {
            return [];
        }
        return [{ childKey: step.childKey, blocker }];
    });
}
function areOpenBlockersOnlyUnresolvedMaterializedControllerChildren(input) {
    const controllerChildIssueIds = new Set((0, workflow_structure_1.resolveWorkflowChildIssueSteps)(input.workflowState).flatMap((step) => {
        if (step.result !== null) {
            return [];
        }
        const issueId = (0, shared_1.normalizeControllerChildIssueRef)(step.childIssueRef);
        return issueId === null ? [] : [issueId];
    }));
    return input.blockers.every((blocker) => controllerChildIssueIds.has(blocker.id));
}
