"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.scanClosedFollowupRequests = scanClosedFollowupRequests;
const post_completion_comments_1 = require("../../issues/post-completion-comments");
const workflow_labels_1 = require("../../platform/ticket-tracker/workflow-labels");
const terminal_followup_1 = require("../../run/run-once-cycle/terminal-followup");
const auth_message_sanitizer_1 = require("../auth-message-sanitizer");
const config_scan_helpers_1 = require("./config-scan-helpers");
const drain_1 = require("./drain");
async function scanClosedFollowupRequests(input) {
    const responseLanguage = input.config.i18n.defaultLanguage;
    const aiFollowUpLabel = (0, workflow_labels_1.getFollowupRequestLabelName)(input.config.ticketTracker.workflowLabels);
    if (input.drainSignal && (await (0, drain_1.isServiceDrainRequested)(input.drainSignal))) {
        return { completed: false };
    }
    const requestedIssues = await input.ticketTracker.listIssueRecords({
        state: "closed",
        labelNames: [aiFollowUpLabel],
        includeSourceBranchName: false,
    });
    const issues = dedupeClosedFollowupCandidates([
        ...requestedIssues,
        ...(input.candidateIssues ?? []),
    ]);
    let completed = true;
    for (const issue of issues) {
        if (input.drainSignal &&
            (await (0, drain_1.isServiceDrainRequested)(input.drainSignal))) {
            completed = false;
            break;
        }
        const hasRequestLabel = hasFollowupRequestLabel({
            issue,
            label: aiFollowUpLabel,
        });
        const scanState = await (0, config_scan_helpers_1.resolveWorkflowScanState)({
            ticketTracker: input.ticketTracker,
            issue,
            responseLanguage,
        });
        if (scanState.canonicalWorkflowStateError !== null) {
            if (hasRequestLabel) {
                logSkippedInvalidCanonicalFollowupSource({
                    issue,
                    reason: scanState.canonicalWorkflowStateError.summary,
                    responseLanguage,
                });
            }
            continue;
        }
        if (!hasRequestLabel &&
            !hasClosedCanonicalFollowupRequest(scanState.stickyState)) {
            continue;
        }
        if (!(0, terminal_followup_1.isEligibleFollowupSource)(issue)) {
            continue;
        }
        const worker = requiresProposalReviewWorker(scanState.stickyState, scanState)
            ? await resolveClosedFollowupWorker(input)
            : input.worker;
        const publicationOutcome = await (0, terminal_followup_1.publishSourceFollowupIssueIfNeeded)({
            context: {
                cwd: input.cwd,
                workflowTemplateRepoRoot: input.workflowTemplateRepoRoot,
                config: input.config,
                ticketTracker: input.ticketTracker,
                ...(worker !== undefined ? { worker } : {}),
                ...(input.currentUserLogin !== undefined
                    ? { currentUserLogin: input.currentUserLogin }
                    : {}),
            },
            workflowLabels: input.config.ticketTracker.workflowLabels,
            sourceIssue: issue,
            sourceWorkflowState: scanState.stickyState,
            responseLanguage: scanState.responseLanguage,
            materializeWorkflowState: hasRequestLabel,
            clearRequestLabelOnSuccess: true,
            publishFeedback: false,
        });
        if (publicationOutcome.result === null) {
            continue;
        }
        await publishClosedFollowupPublicationState({
            cwd: input.cwd,
            workflowTemplateRepoRoot: input.workflowTemplateRepoRoot,
            config: input.config,
            ticketTracker: input.ticketTracker,
            issue,
            workflowState: publicationOutcome.workflowState,
            responseLanguage: scanState.responseLanguage,
            currentUserLogin: input.currentUserLogin,
            clearRequestLabel: publicationOutcome.shouldClearRequestLabel,
        });
    }
    return { completed };
}
async function resolveClosedFollowupWorker(input) {
    if (input.worker !== undefined) {
        return input.worker;
    }
    return input.loadWorker === undefined ? undefined : input.loadWorker();
}
function requiresProposalReviewWorker(stickyState, scanState) {
    const proposal = stickyState?.followup?.proposal;
    if (proposal === undefined || proposal === null) {
        return false;
    }
    return ((0, post_completion_comments_1.selectPostCompletionUserComments)({
        comments: scanState.comments,
        completedAt: proposal.createdAt,
    }).length > 0);
}
function logSkippedInvalidCanonicalFollowupSource(input) {
    console.error(`[service-followup-scan] Skipped ${input.issue.displayId}: ${(0, auth_message_sanitizer_1.sanitizeAuthMessage)(input.reason, input.responseLanguage)}`);
}
async function publishClosedFollowupPublicationState(input) {
    if (input.workflowState === null) {
        return;
    }
    await (0, terminal_followup_1.publishFollowupSourceWorkflowState)({
        context: {
            cwd: input.cwd,
            workflowTemplateRepoRoot: input.workflowTemplateRepoRoot,
            config: input.config,
            ticketTracker: input.ticketTracker,
            ...(input.currentUserLogin !== undefined
                ? { currentUserLogin: input.currentUserLogin }
                : {}),
        },
        sourceIssue: input.issue,
        workflowState: input.workflowState,
        responseLanguage: input.responseLanguage,
        clearRequestLabel: input.clearRequestLabel,
    });
}
function dedupeClosedFollowupCandidates(issues) {
    const byId = new Map();
    for (const issue of issues) {
        if (!issue.isOpen) {
            byId.set(issue.id, issue);
        }
    }
    return [...byId.values()];
}
function hasClosedCanonicalFollowupRequest(stickyState) {
    const followup = stickyState?.followup;
    if (followup === undefined || followup.proposalPolicy === "off") {
        return false;
    }
    if (followup.proposal !== undefined && followup.proposal !== null) {
        return false;
    }
    const publications = followup.publications ?? [];
    const hasCompletedPublication = publications.some((publication) => publication.status === "created" ||
        publication.status === "reused" ||
        publication.status === "skipped");
    if (hasCompletedPublication) {
        return false;
    }
    if (followup.proposalPolicy === "always") {
        return true;
    }
    return followup.recommendation?.recommended === true;
}
function hasFollowupRequestLabel(input) {
    return input.issue.labelNames?.includes(input.label) ?? false;
}
