"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadServiceWorkflowGraphContext = loadServiceWorkflowGraphContext;
exports.sortServiceTasksByWorkflowFrontier = sortServiceTasksByWorkflowFrontier;
exports.collectWorkflowSubtreeIssueIds = collectWorkflowSubtreeIssueIds;
const workflow_issue_graph_1 = require("../../run/workflow-issue-graph");
const repo_helpers_1 = require("./repo-helpers");
async function loadServiceWorkflowGraphContext(input) {
    const workflowGraphIssues = dedupeIssuesById(input.openIssues.filter((issue) => !(0, repo_helpers_1.shouldSkipForServiceRuleLabels)(issue.workflowState.rules)));
    const workflowStateByIssueId = await (0, repo_helpers_1.loadPersistedWorkflowStatesForIssues)(input.ticketTracker, workflowGraphIssues);
    return {
        workflowGraph: (0, workflow_issue_graph_1.buildWorkflowIssueGraph)(workflowGraphIssues.map((issue) => ({
            issue,
            workflowState: workflowStateByIssueId.get(issue.id) ?? null,
        }))),
        workflowGraphIssues,
        workflowStateByIssueId,
    };
}
function sortServiceTasksByWorkflowFrontier(tasks, graph, workflowStateByIssueId) {
    return [...tasks].sort((left, right) => (0, workflow_issue_graph_1.compareWorkflowFrontierPriority)({
        issueId: left.issue.id,
        workflowState: workflowStateByIssueId.get(left.issue.id) ?? null,
    }, {
        issueId: right.issue.id,
        workflowState: workflowStateByIssueId.get(right.issue.id) ?? null,
    }, graph));
}
function collectWorkflowSubtreeIssueIds(issueId, graph) {
    const issueIds = new Set();
    const pendingIssueIds = [issueId];
    while (pendingIssueIds.length > 0) {
        const nextIssueId = pendingIssueIds.pop();
        if (nextIssueId === undefined || issueIds.has(nextIssueId)) {
            continue;
        }
        issueIds.add(nextIssueId);
        const node = graph.nodeByIssueId.get(nextIssueId);
        if (node === undefined) {
            continue;
        }
        pendingIssueIds.push(...node.childIssueIds);
    }
    return [...issueIds];
}
function dedupeIssuesById(issues) {
    return [
        ...new Map(issues.map((issue) => [issue.id, issue])).values(),
    ];
}
