"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.publishDependencyCompletionRequeue = publishDependencyCompletionRequeue;
exports.persistDependencySyncState = persistDependencySyncState;
const canonical_workflow_state_1 = require("../../comments/canonical-workflow-state");
const workflow_update_1 = require("../../comments/workflow-update");
const catalog_1 = require("../../i18n/catalog");
const types_1 = require("../../platform/ticket-tracker/types");
const types_2 = require("../../platform/workflow-state/types");
const publish_precondition_support_1 = require("../../workflows/publish-precondition-support");
const publisher_shared_1 = require("../../workflows/publisher-shared");
const visible_update_builders_1 = require("../../workflows/visible-update-builders");
const publisher_events_1 = require("../../workflows/publisher-events");
const needs_human_merge_state_1 = require("./needs-human-merge-state");
const needs_human_merge_support_1 = require("./needs-human-merge-support");
const publisher_factory_1 = require("./publisher-factory");
const same_issue_replan_publication_1 = require("./same-issue-replan-publication");
const same_issue_replan_state_support_1 = require("./same-issue-replan-state-support");
const shared_1 = require("./shared");
async function publishDependencyCompletionRequeue(input) {
    const issueComments = await (0, shared_1.loadSortedIssueComments)(input.context.ticketTracker, input.targetIssue.id, {
        timeline: "issue-only",
    });
    const workflowStateResolution = (0, canonical_workflow_state_1.resolveCanonicalWorkflowStateComment)(issueComments, input.locale);
    const resolvedWorkflowState = workflowStateResolution.kind === "found"
        ? workflowStateResolution.workflowState
        : null;
    const previousWorkflowState = input.currentWorkflowState ?? resolvedWorkflowState;
    if (previousWorkflowState === null) {
        return {
            publication: null,
            accepted: false,
            workflowStateChanged: false,
        };
    }
    const previousNeedsHumanReason = input.previousNeedsHumanReason ?? (0, workflow_update_1.findLatestNeedsHumanReason)(issueComments);
    const summary = (0, needs_human_merge_support_1.buildDependencyIntegratedSummary)(input.locale);
    const nextWorkflowStateBase = input.nextWorkflowState ?? previousWorkflowState;
    const nextWorkflowState = input.targetIssue.kind === types_1.TRACKER_ITEM_KINDS.pullRequest
        ? (0, needs_human_merge_state_1.resolvePullRequestMergeReplanWorkflowState)({
            workflowState: nextWorkflowStateBase,
            pendingPlanningReason: summary,
            pendingPlanningSource: "dependency_completion",
        })
        : (0, same_issue_replan_state_support_1.deriveSameIssueReplanWorkflowState)({
            kind: "dependency_completion_requeue",
            previousWorkflowState,
            nextWorkflowState: nextWorkflowStateBase,
            reason: summary,
        });
    delete nextWorkflowState.autoMergeState;
    delete nextWorkflowState.pendingWorkflowStartApprovalIntent;
    const nextProjection = resolveDependencyCompletionNextSnapshot({
        issue: input.targetIssue,
    });
    const nextNeedsHumanReason = nextProjection.status === types_2.WORKFLOW_STATUSES.aiNeedsHuman
        ? previousNeedsHumanReason
        : null;
    const request = (0, same_issue_replan_publication_1.buildSameIssueReplanPublishRequest)({
        intent: {
            kind: "dependency_completion_requeue",
            issue: input.targetIssue,
            previousWorkflowState,
            publishPrecondition: (0, publish_precondition_support_1.buildWorkflowPublishPrecondition)({
                currentWorkflowStateCommentId: workflowStateResolution.kind === "found"
                    ? workflowStateResolution.comment.id
                    : null,
                workflowState: previousWorkflowState,
            }),
            nextWorkflowState,
            previousProjection: input.targetIssue.workflowState,
            nextProjection,
            previousNeedsHumanReason,
            nextNeedsHumanReason,
            visibleUpdate: buildDependencyCompletionVisibleUpdate({
                locale: input.locale,
                issue: input.targetIssue,
                nextProjectionStatus: nextProjection.status,
                needsHumanReason: nextNeedsHumanReason,
                completedDependencyIssueIds: input.completedDependencyIssueIds ?? [],
            }),
            reason: summary,
        },
        issueComments,
        workflowLabels: input.context.config.ticketTracker.workflowLabels,
        responseLanguage: input.locale,
    });
    if (request === null) {
        return {
            publication: null,
            accepted: false,
            workflowStateChanged: false,
        };
    }
    const publication = await createDependencyPublisher(input.context).publishWorkflow(request);
    const applied = publication.publishStatus === "applied";
    return {
        publication,
        accepted: applied,
        workflowStateChanged: applied,
    };
}
async function persistDependencySyncState(input) {
    const publisher = (0, publisher_factory_1.createRunWorkflowPublisher)(input.context);
    await publisher.publishWorkflow({
        target: {
            kind: "existing_issue",
            issueId: input.issueId,
        },
        workflowState: input.workflowState,
        ...(input.visibleUpdate !== undefined
            ? { visibleUpdate: input.visibleUpdate }
            : {}),
        commentCursorPolicy: {
            mode: publisher_shared_1.WORKFLOW_COMMENT_CURSOR_POLICY_MODES.preserve,
        },
        responseLanguage: input.locale,
    });
}
function buildDependencyCompletionVisibleUpdate(input) {
    const dedupeKey = resolveDependencyCompletionDedupeKey(input.completedDependencyIssueIds);
    if (input.nextProjectionStatus === types_2.WORKFLOW_STATUSES.aiNeedsHuman) {
        return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
            event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.dependencyIntegrated,
            summary: (0, needs_human_merge_support_1.buildDependencyIntegratedSummary)(input.locale),
            next: resolveDependencyIntegratedNeedsHumanNext(input),
            needsHumanReason: input.needsHumanReason,
            ...(dedupeKey !== null ? { dedupeKey } : {}),
        });
    }
    return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
        event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.dependencyIntegrated,
        summary: (0, needs_human_merge_support_1.buildDependencyIntegratedSummary)(input.locale),
        next: (0, needs_human_merge_support_1.buildDependencyIntegratedNextMessage)(input.locale),
        ...(dedupeKey !== null ? { dedupeKey } : {}),
    });
}
function resolveDependencyCompletionDedupeKey(completedDependencyIssueIds) {
    const sortedIds = [...new Set(completedDependencyIssueIds)]
        .map((issueId) => issueId.trim())
        .filter((issueId) => issueId.length > 0)
        .sort((left, right) => left.localeCompare(right, undefined, {
        numeric: true,
    }));
    return sortedIds.length > 0
        ? `dependency-completion:${sortedIds.join(",")}`
        : null;
}
function resolveDependencyCompletionNextSnapshot(input) {
    if (input.issue.workflowState.status === types_2.WORKFLOW_STATUSES.aiNeedsHuman) {
        return {
            status: types_2.WORKFLOW_STATUSES.aiNeedsHuman,
            rules: [...input.issue.workflowState.rules],
        };
    }
    return {
        status: types_2.WORKFLOW_STATUSES.aiReady,
        rules: [...input.issue.workflowState.rules],
    };
}
function createDependencyPublisher(context) {
    return (0, publisher_factory_1.createRunWorkflowPublisher)(context);
}
function resolveDependencyIntegratedNeedsHumanNext(input) {
    if (input.issue.kind === types_1.TRACKER_ITEM_KINDS.pullRequest &&
        input.needsHumanReason === publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.reviewReady) {
        return (0, catalog_1.translate)(input.locale, "run.needsHuman.merge.dependencyIntegrated.needsHuman.reviewReady.next");
    }
    return (0, catalog_1.translate)(input.locale, "run.needsHuman.merge.dependencyIntegrated.needsHuman.next");
}
