"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderSavedAuthLabel = renderSavedAuthLabel;
exports.renderSavedAuthLabelInCollection = renderSavedAuthLabelInCollection;
exports.buildExecutionFailedSummary = buildExecutionFailedSummary;
exports.buildAiRunLimitSummary = buildAiRunLimitSummary;
exports.appendAiRunLimitHandoffSummary = appendAiRunLimitHandoffSummary;
exports.buildDeferredPresentation = buildDeferredPresentation;
exports.resolveIssuePresentation = resolveIssuePresentation;
exports.buildWorkflowStepSummary = buildWorkflowStepSummary;
exports.renderOutcomeTransitionSection = renderOutcomeTransitionSection;
exports.renderStatusTransitionSection = renderStatusTransitionSection;
exports.renderFinalWorkflowStateSection = renderFinalWorkflowStateSection;
exports.renderDeferredWorkerSection = renderDeferredWorkerSection;
exports.renderCliSummary = renderCliSummary;
exports.formatWorkflowState = formatWorkflowState;
const store_1 = require("../../auth-profiles/store");
const helpers_1 = require("../../comments/canonical-workflow-state/helpers");
const tree_1 = require("../../comments/canonical-workflow-state/tree");
const catalog_1 = require("../../i18n/catalog");
const display_duration_1 = require("../../i18n/display-duration");
const workflow_labels_1 = require("../../platform/ticket-tracker/workflow-labels");
const issue_completion_1 = require("../../config/issue-completion");
const constants_1 = require("../../worker/constants");
const issue_logger_1 = require("../issue-logger");
const log_text_1 = require("../log-text");
function renderSavedAuthLabel(profile, locale = catalog_1.DEFAULT_APP_LOCALE) {
    return (0, store_1.formatAuthProfileBaseLabel)(profile, locale);
}
function renderSavedAuthLabelInCollection(profile, collection, locale = catalog_1.DEFAULT_APP_LOCALE) {
    return (0, store_1.formatAuthProfileLabel)(profile, collection, locale);
}
function buildExecutionFailedSummary(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.presentation.executionFailed");
}
function buildAiRunLimitSummary(responseLanguage, input) {
    const summaryInput = {
        ...input,
        reachedKind: input.reachedKind ?? "max_runs",
    };
    if (summaryInput.reachedKind === "max_hours") {
        return (0, catalog_1.translate)(responseLanguage, "run.presentation.aiRunHoursReached", {
            totalAiRunHours: (0, display_duration_1.formatHumanAiRunHours)(summaryInput.totalAiRunHours, responseLanguage),
            maxAiRunHours: formatNullableAiRunHours(summaryInput.maxHours, responseLanguage),
        });
    }
    return (0, catalog_1.translate)(responseLanguage, "run.presentation.consecutiveAiRunsReached", {
        consecutiveAiRuns: summaryInput.consecutiveAiRuns,
        maxRuns: summaryInput.maxRuns,
    });
}
function appendSentence(base, sentence) {
    if (base.includes(sentence)) {
        return base;
    }
    if (base.length === 0) {
        return sentence;
    }
    return `${base}\n\n${sentence}`;
}
function appendAiRunLimitHandoffSummary(responseLanguage, summary, input) {
    const summaryInput = {
        ...input,
        reachedKind: input.reachedKind ?? "max_runs",
    };
    if (summaryInput.reachedKind === "max_hours") {
        return appendSentence(summary, (0, catalog_1.translate)(responseLanguage, "run.presentation.aiRunHoursReachedHandoff", {
            totalAiRunHours: (0, display_duration_1.formatHumanAiRunHours)(summaryInput.totalAiRunHours, responseLanguage),
            maxAiRunHours: formatNullableAiRunHours(summaryInput.maxHours, responseLanguage),
        }));
    }
    return appendSentence(summary, (0, catalog_1.translate)(responseLanguage, "run.presentation.consecutiveAiRunsReachedHandoff", {
        consecutiveAiRuns: summaryInput.consecutiveAiRuns,
        maxRuns: summaryInput.maxRuns,
    }));
}
function formatNullableAiRunHours(maxHours, locale) {
    return maxHours === null
        ? (0, catalog_1.translate)(locale, "run.presentation.aiRunHoursOff")
        : (0, display_duration_1.formatHumanAiRunHours)(maxHours, locale);
}
function buildDeferredPresentation(responseLanguage, cooldownUntil, triedProfiles) {
    return {
        summary: (0, catalog_1.translate)(responseLanguage, "run.presentation.deferredSummary"),
        next: [
            cooldownUntil
                ? (0, catalog_1.translate)(responseLanguage, "run.presentation.deferredNext.retryAfter", {
                    cooldownUntil,
                })
                : (0, catalog_1.translate)(responseLanguage, "run.presentation.deferredNext.retryWhenCooldownEnds"),
            (0, catalog_1.translate)(responseLanguage, "run.presentation.deferredNext.triedProfiles", {
                triedProfiles: (0, issue_logger_1.formatList)(triedProfiles),
            }),
        ].join(" "),
    };
}
function resolveIssuePresentation({ finalOutcome, facts, summary, comment, result, consecutiveAiRuns, responseLanguage, readyLabel, workflowState, isPullRequest = false, handoffToPr, handoffPullRequestStatus, handoffIssueCompletion, needsHumanReason, terminalSuccess = false, }) {
    const commentSummary = finalOutcome === constants_1.WORKER_OUTCOMES.waitHuman
        ? buildWaitHumanOutcomeSummary({
            summary,
            comment,
            result,
            workflowState,
            responseLanguage,
            needsHumanReason,
        })
        : buildCommentSummary(summary, comment);
    const renderedCommentSummary = workflowState !== null &&
        hasRenderableWorkflowStep(workflowState) &&
        finalOutcome === constants_1.WORKER_OUTCOMES.proceed &&
        !terminalSuccess
        ? buildWorkflowStepSummary(workflowState, responseLanguage)
        : commentSummary;
    switch (finalOutcome) {
        case constants_1.WORKER_OUTCOMES.proceed:
            if (handoffToPr) {
                return {
                    commentOutcome: constants_1.WORKER_OUTCOMES.proceed,
                    commentSummary: renderedCommentSummary,
                    commentNext: buildPrHandoffNextStep(responseLanguage, handoffPullRequestStatus === "ai-ready", handoffIssueCompletion),
                    commentConsecutiveAiRuns: consecutiveAiRuns,
                    cliNext: buildPrHandoffNextStep(responseLanguage, handoffPullRequestStatus === "ai-ready", handoffIssueCompletion),
                };
            }
            if (terminalSuccess) {
                const next = (0, catalog_1.translate)(responseLanguage, isPullRequest
                    ? "run.presentation.terminalSuccessPrNext"
                    : "run.presentation.terminalSuccessIssueNext");
                return {
                    commentOutcome: constants_1.WORKER_OUTCOMES.proceed,
                    commentSummary: renderedCommentSummary,
                    commentNext: next,
                    commentConsecutiveAiRuns: consecutiveAiRuns,
                    cliNext: next,
                };
            }
            return {
                commentOutcome: constants_1.WORKER_OUTCOMES.proceed,
                commentSummary: renderedCommentSummary,
                commentNext: (0, catalog_1.translate)(responseLanguage, "run.presentation.proceedNext"),
                commentConsecutiveAiRuns: consecutiveAiRuns,
                cliNext: (0, catalog_1.translate)(responseLanguage, facts.branchAheadOfBase && !facts.openPullRequestExists
                    ? "run.presentation.proceedCliNext.createdDraftPr"
                    : "run.presentation.proceedCliNext.queued"),
            };
        case constants_1.WORKER_OUTCOMES.waitHuman:
            if (handoffToPr) {
                return {
                    commentOutcome: constants_1.WORKER_OUTCOMES.waitHuman,
                    commentSummary: renderedCommentSummary,
                    commentNext: buildPrHandoffNextStep(responseLanguage, handoffPullRequestStatus === "ai-ready", handoffIssueCompletion),
                    commentConsecutiveAiRuns: consecutiveAiRuns,
                    cliNext: buildPrHandoffNextStep(responseLanguage, handoffPullRequestStatus === "ai-ready", handoffIssueCompletion),
                };
            }
            return buildStoppedPresentation({
                finalOutcome: constants_1.WORKER_OUTCOMES.waitHuman,
                summary: renderedCommentSummary,
                questionAction: result?.humanComment ?? null,
                consecutiveAiRuns,
                responseLanguage,
                readyLabel,
                isPullRequest,
                needsHumanReason,
            });
        case constants_1.WORKER_OUTCOMES.fail:
            return buildStoppedPresentation({
                finalOutcome: constants_1.WORKER_OUTCOMES.fail,
                summary: renderedCommentSummary,
                consecutiveAiRuns,
                responseLanguage,
                readyLabel,
                isPullRequest,
            });
    }
}
function buildPrHandoffNextStep(responseLanguage, queuedForAi, issueCompletion) {
    if (queuedForAi) {
        if (issueCompletion !== undefined &&
            (0, issue_completion_1.shouldSkipPullRequestReview)(issueCompletion) &&
            (0, issue_completion_1.isPullRequestAutoMergePolicyEnabled)(issueCompletion)) {
            return (0, catalog_1.translate)(responseLanguage, "run.presentation.prHandoff.next.autoMerge");
        }
        return (0, catalog_1.translate)(responseLanguage, "run.presentation.prHandoff.next.queued");
    }
    return (0, catalog_1.translate)(responseLanguage, "run.presentation.prHandoff.next.review");
}
function hasRenderableWorkflowStep(workflowState) {
    return workflowState.plan !== null && workflowState.plan.steps.length > 0;
}
function buildWorkflowStepSummary(workflowState, responseLanguage = catalog_1.DEFAULT_APP_LOCALE) {
    const plan = workflowState.plan;
    if (plan === null || plan.steps.length === 0) {
        return (0, catalog_1.translate)(responseLanguage, "canonicalWorkflowComment.currentStatusCurrentStepUnavailableLabel");
    }
    const progress = (0, tree_1.selectWorkflowPlanProgress)(plan);
    if (progress.isCompleted) {
        return `${(0, catalog_1.translate)(responseLanguage, "canonicalWorkflowComment.currentStatusDoneLabel")} (${plan.steps.length}/${plan.steps.length})`;
    }
    const currentStepIndex = progress.currentStepIndex;
    if (currentStepIndex === null) {
        return (0, catalog_1.translate)(responseLanguage, "canonicalWorkflowComment.currentStatusCurrentStepUnavailableLabel");
    }
    const currentStep = plan.steps[currentStepIndex];
    if (currentStep === undefined) {
        return (0, catalog_1.translate)(responseLanguage, "canonicalWorkflowComment.currentStatusCurrentStepUnavailableLabel");
    }
    return `${(0, catalog_1.translate)(responseLanguage, "canonicalWorkflowComment.currentStatusInProgressLabel")} (${currentStepIndex + 1}/${plan.steps.length}) ${(0, helpers_1.renderWorkflowStepTitleWithIssueRef)(currentStep)}`;
}
function buildStoppedPresentation(input) {
    const questionAction = input.finalOutcome === constants_1.WORKER_OUTCOMES.waitHuman &&
        input.needsHumanReason === "question"
        ? normalizeSummaryBlockText(input.questionAction)
        : null;
    if (questionAction !== null) {
        const cliResumeInstruction = buildCliResumeInstruction(input.responseLanguage, input.readyLabel, input.isPullRequest);
        return {
            commentOutcome: input.finalOutcome,
            commentSummary: input.summary,
            commentNext: questionAction,
            commentConsecutiveAiRuns: input.consecutiveAiRuns,
            cliNext: [questionAction, cliResumeInstruction].join("\n\n"),
        };
    }
    const nextKey = resolveStoppedPresentationNextKey(input.finalOutcome, input.isPullRequest, input.needsHumanReason);
    const fallbackNext = (0, catalog_1.translate)(input.responseLanguage, nextKey);
    const commentResumeInstruction = buildResumeInstruction(input.responseLanguage, input.readyLabel, input.isPullRequest);
    const cliResumeInstruction = buildCliResumeInstruction(input.responseLanguage, input.readyLabel, input.isPullRequest);
    return {
        commentOutcome: input.finalOutcome,
        commentSummary: input.summary,
        commentNext: joinTranslatedSentences(input.responseLanguage, fallbackNext, commentResumeInstruction),
        commentConsecutiveAiRuns: input.consecutiveAiRuns,
        cliNext: joinTranslatedSentences(input.responseLanguage, fallbackNext, cliResumeInstruction),
    };
}
function resolveStoppedPresentationNextKey(finalOutcome, isPullRequest, needsHumanReason) {
    if (finalOutcome === constants_1.WORKER_OUTCOMES.waitHuman) {
        if (needsHumanReason === "timeout") {
            return "run.presentation.waitHumanTimeoutNext";
        }
        if (needsHumanReason === "system_error") {
            return "run.presentation.waitHumanSystemErrorNext";
        }
        if (!isPullRequest && needsHumanReason === "review_ready") {
            return "run.presentation.waitHumanIssueReviewNext";
        }
        return isPullRequest
            ? "run.presentation.waitHumanPrNext"
            : "run.presentation.waitHumanNext";
    }
    return "run.presentation.failNext";
}
function renderOutcomeTransitionSection({ workflowLabels, from, to, requestedOutcome, finalOutcome, facts, locale = catalog_1.DEFAULT_APP_LOCALE, }) {
    void locale;
    return [
        (0, log_text_1.issueLogField)("from", (0, workflow_labels_1.getWorkflowLabelForStatus)(workflowLabels, from)),
        (0, log_text_1.issueLogField)("requestedOutcome", requestedOutcome),
        (0, log_text_1.issueLogField)("finalOutcome", finalOutcome),
        (0, log_text_1.issueLogField)("to", (0, workflow_labels_1.getWorkflowLabelForStatus)(workflowLabels, to)),
        (0, log_text_1.issueLogField)("branchAheadOfBase", (0, log_text_1.formatLogBoolean)(facts.branchAheadOfBase)),
        (0, log_text_1.issueLogField)("openPrExists", (0, log_text_1.formatLogBoolean)(facts.openPullRequestExists)),
    ].join("\n");
}
function renderStatusTransitionSection({ workflowLabels, from, to, facts, note, locale = catalog_1.DEFAULT_APP_LOCALE, }) {
    void locale;
    return [
        (0, log_text_1.issueLogField)("from", (0, workflow_labels_1.getWorkflowLabelForStatus)(workflowLabels, from)),
        (0, log_text_1.issueLogField)("note", note),
        (0, log_text_1.issueLogField)("to", (0, workflow_labels_1.getWorkflowLabelForStatus)(workflowLabels, to)),
        (0, log_text_1.issueLogField)("branchAheadOfBase", (0, log_text_1.formatLogBoolean)(facts.branchAheadOfBase)),
        (0, log_text_1.issueLogField)("openPrExists", (0, log_text_1.formatLogBoolean)(facts.openPullRequestExists)),
    ].join("\n");
}
function renderFinalWorkflowStateSection(snapshot, isClosed, workflowLabels, locale = catalog_1.DEFAULT_APP_LOCALE) {
    void locale;
    return [
        (0, log_text_1.issueLogField)("workflow", formatWorkflowState(workflowLabels, snapshot)),
        (0, log_text_1.issueLogField)("closed", (0, log_text_1.formatLogBoolean)(isClosed)),
    ].join("\n");
}
function renderDeferredWorkerSection(deferred, locale = catalog_1.DEFAULT_APP_LOCALE) {
    void locale;
    const lines = [
        (0, log_text_1.issueLogField)("deferredReason", deferred.deferredReason),
        (0, log_text_1.issueLogField)("triedSignIns", (0, issue_logger_1.formatList)(deferred.triedProfiles)),
        (0, log_text_1.issueLogField)("cooldownUntil", (0, issue_logger_1.formatNullable)(deferred.cooldownUntil)),
    ];
    return lines.join("\n");
}
function renderCliSummary(summary, locale = catalog_1.DEFAULT_APP_LOCALE) {
    void locale;
    const lines = [
        (0, log_text_1.issueLogField)("headline", summary.headline),
        (0, log_text_1.issueLogField)("outcome", summary.outcome),
        (0, log_text_1.issueLogField)("issueUrl", summary.issue_url),
        (0, log_text_1.issueLogField)("commentUrl", (0, issue_logger_1.formatNullable)(summary.comment_url)),
        (0, log_text_1.issueLogField)("pr", (0, issue_logger_1.formatNullable)(summary.pr_url)),
        (0, log_text_1.issueLogField)("nextStep", summary.next_step),
    ];
    if (summary.deferred_reason) {
        lines.push((0, log_text_1.issueLogField)("deferredReason", summary.deferred_reason), (0, log_text_1.issueLogField)("triedSignIns", (0, issue_logger_1.formatList)(summary.tried_profiles)), (0, log_text_1.issueLogField)("cooldownUntil", (0, issue_logger_1.formatNullable)(summary.cooldown_until)));
    }
    if (summary.interrupt_reason) {
        lines.push((0, log_text_1.issueLogField)("interruptReason", summary.interrupt_reason));
    }
    return lines.join("\n");
}
function formatWorkflowState(workflowLabels, snapshot) {
    return (0, workflow_labels_1.formatWorkflowLabelNames)(workflowLabels, snapshot);
}
function buildCommentSummary(summary, comment) {
    if (!comment) {
        return summary;
    }
    return `${summary}\n\n${comment}`;
}
function buildWaitHumanOutcomeSummary(input) {
    const isQuestionHandoff = input.needsHumanReason === "question";
    const sections = [
        buildCommentSummary(input.summary, isQuestionHandoff ? null : input.comment),
    ];
    const stopReasonLines = isQuestionHandoff
        ? []
        : resolveStopReasonLines(input.result);
    const stopReasonSection = renderDistinctSummarySection(sections, (0, catalog_1.translate)(input.responseLanguage, "run.presentation.stopReasonLabel"), stopReasonLines);
    if (stopReasonSection !== null) {
        sections.push(stopReasonSection);
    }
    const resultSummary = resolveCompletedResultSummary(input.workflowState, input.result);
    const resultSection = renderDistinctSummarySection(sections, (0, catalog_1.translate)(input.responseLanguage, "run.presentation.resultLabel"), resultSummary === null ? [] : [resultSummary]);
    if (resultSection !== null) {
        sections.push(resultSection);
    }
    return sections.join("\n\n");
}
function resolveStopReasonLines(result) {
    if (result === null || result === undefined) {
        return [];
    }
    const humanComment = extractFirstParagraph(result.humanComment);
    if (humanComment !== null) {
        return [humanComment];
    }
    return [];
}
function resolveCompletedResultSummary(workflowState, result) {
    const progress = (0, tree_1.selectWorkflowPlanProgress)(workflowState?.plan ?? null);
    if (!progress.isCompleted) {
        return null;
    }
    return normalizeSummaryBlockText(result?.resultSummary ?? null);
}
function renderDistinctSummarySection(existingSections, heading, lines) {
    const body = lines
        .map((line) => normalizeSummaryBlockText(line))
        .filter((line) => line !== null)
        .join("\n");
    if (body.length === 0) {
        return null;
    }
    if (existingSections.some((section) => section.includes(body))) {
        return null;
    }
    return `${heading}:\n${body}`;
}
function extractFirstParagraph(value) {
    const normalized = normalizeSummaryBlockText(value);
    if (normalized === null) {
        return null;
    }
    const [paragraph] = normalized.split(/\n\s*\n/u, 1);
    return normalizeSummaryBlockText(paragraph);
}
function normalizeSummaryBlockText(value) {
    if (typeof value !== "string") {
        return null;
    }
    const trimmed = value.trim();
    return trimmed.length === 0 ? null : trimmed;
}
function buildResumeInstruction(responseLanguage, readyLabel, isPullRequest = false) {
    return (0, catalog_1.translate)(responseLanguage, isPullRequest
        ? "run.presentation.resumePr.comment"
        : "run.presentation.resume.comment", {
        readyLabel,
    });
}
function buildCliResumeInstruction(responseLanguage, readyLabel, isPullRequest = false) {
    return (0, catalog_1.translate)(responseLanguage, isPullRequest
        ? "run.presentation.resumePr.cli"
        : "run.presentation.resume.cli", {
        readyLabel,
    });
}
function joinTranslatedSentences(responseLanguage, first, second) {
    return responseLanguage === "en" ? `${first} ${second}` : `${first}${second}`;
}
