"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderIssueShow = renderIssueShow;
const catalog_1 = require("../../i18n/catalog");
const issue_report_1 = require("../../issues/issue-report");
const types_1 = require("../../issues/types");
const auto_merge_state_1 = require("../../workflows/auto-merge-state");
const publisher_events_1 = require("../../workflows/publisher-events");
const comments_1 = require("./comments");
const format_1 = require("./format");
const origins_1 = require("./origins");
const pull_request_details_1 = require("./pull-request-details");
const workflow_template_labels_1 = require("./workflow-template-labels");
function renderIssueShow(viewModel, format, locale = catalog_1.DEFAULT_APP_LOCALE, displayTimeZone = "UTC") {
    return format === types_1.ISSUE_REPORT_FORMATS.markdown
        ? renderMarkdownIssueShow(viewModel, locale, displayTimeZone)
        : renderTextIssueShow(viewModel, locale, displayTimeZone);
}
function renderMarkdownIssueShow(viewModel, locale, displayTimeZone) {
    const lines = [
        (0, catalog_1.translate)(locale, viewModel.isManaged
            ? "issue.command.show.markdownTitle"
            : "issue.command.show.markdownTitleUnmanaged", {
            issue: (0, format_1.formatIssueReference)(viewModel.issue.displayId, viewModel.issue.url, types_1.ISSUE_REPORT_FORMATS.markdown),
            title: (0, format_1.escapeMarkdownTitle)(viewModel.issue.title),
        }),
        "",
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.url", {
            value: (0, format_1.formatIssueReference)(viewModel.issue.url, viewModel.issue.url, types_1.ISSUE_REPORT_FORMATS.markdown),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.state", {
            value: viewModel.stateLabel,
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.assignees", {
            value: (0, format_1.escapeMarkdownText)(viewModel.assigneesLabel),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.blockedBy", {
            value: (0, format_1.escapeMarkdownText)(viewModel.blockingLabel),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.pendingDependencySync", {
            value: (0, format_1.escapeMarkdownText)(viewModel.pendingDependencySyncLabel),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.dependencySyncHistory", {
            value: (0, format_1.escapeMarkdownText)(viewModel.dependencySyncHistoryLabel),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.workflow", {
            value: (0, format_1.escapeMarkdownText)(viewModel.workflowTemplateLabel ??
                (0, catalog_1.translate)(locale, "workflow.runContext.none")),
        })}`,
        ...workflow_template_labels_1.SIDE_WORKFLOW_TEMPLATE_DISPLAY_SPECS.map((spec) => `- ${(0, catalog_1.translate)(locale, spec.showKey, {
            value: (0, format_1.escapeMarkdownText)((0, workflow_template_labels_1.resolveWorkflowTemplateLabelValue)(viewModel.workflowTemplateLabelsBySurface, spec.surface, locale)),
        })}`),
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.followupProposalPolicy", {
            value: (0, format_1.escapeMarkdownText)(viewModel.followupProposalPolicy ?? "off"),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.followupProposalApproval", {
            value: (0, format_1.escapeMarkdownText)(viewModel.followupProposalApproval ?? "auto"),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.report.item.updated", {
            updatedAt: viewModel.updatedAtLabel,
        })}`,
        ...((viewModel.completedAtLabel ?? null) !== null
            ? [
                `- ${(0, catalog_1.translate)(locale, "issue.command.show.completed", {
                    value: viewModel.completedAtLabel ?? "",
                })}`,
            ]
            : []),
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.workflowStatus", {
            value: (0, format_1.escapeMarkdownText)(viewModel.workflowStatusLabel),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.ruleLabels", {
            value: (0, format_1.escapeMarkdownText)(viewModel.ruleLabelsLabel),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.relatedPr", {
            value: (0, format_1.formatRelatedPullRequestMarkdown)(viewModel.pr),
        })}`,
        ...(0, pull_request_details_1.renderMarkdownPullRequestDetails)(viewModel, locale),
        ...(viewModel.activeOverrideDetails.length > 0
            ? [
                `- ${(0, catalog_1.translate)(locale, "issue.command.show.activeOverrides", {
                    value: (0, format_1.escapeMarkdownText)(viewModel.activeOverrideDetails.join(" | ")),
                })}`,
            ]
            : []),
        "",
        `**${(0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowStateHeading")}**`,
        ...renderMarkdownCanonicalWorkflowState(viewModel.issue.isOpen, viewModel.issue.workflowState, viewModel.canonicalWorkflowState, locale),
        ...(0, origins_1.renderOptionalMarkdownOriginIssues)(viewModel, locale),
        ...renderOptionalMarkdownChildIssues(viewModel, locale),
        ...(0, comments_1.renderOptionalMarkdownPostCompletionComments)(viewModel, locale, displayTimeZone),
        "",
        `**${viewModel.latestUpdateHeadingLabel}**`,
        ...renderMarkdownLatestUpdate(viewModel.latestUpdate, locale, displayTimeZone),
        "",
        `**${(0, catalog_1.translate)(locale, "issue.command.show.bodyHeading")}**`,
        ...renderMarkdownBody(viewModel.issue.body, locale),
        ...(0, comments_1.renderOptionalMarkdownComments)(viewModel, locale, displayTimeZone),
    ];
    return lines.join("\n").trimEnd();
}
function renderTextIssueShow(viewModel, locale, displayTimeZone) {
    const lines = [
        (0, catalog_1.translate)(locale, viewModel.isManaged
            ? "issue.command.show.textTitle"
            : "issue.command.show.textTitleUnmanaged", {
            issue: viewModel.issue.displayId,
            title: viewModel.issue.title,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.url", {
            value: viewModel.issue.url,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.state", {
            value: viewModel.stateLabel,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.assignees", {
            value: viewModel.assigneesLabel,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.blockedBy", {
            value: viewModel.blockingLabel,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.pendingDependencySync", {
            value: viewModel.pendingDependencySyncLabel,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.dependencySyncHistory", {
            value: viewModel.dependencySyncHistoryLabel,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.workflow", {
            value: viewModel.workflowTemplateLabel ??
                (0, catalog_1.translate)(locale, "workflow.runContext.none"),
        }),
        ...workflow_template_labels_1.SIDE_WORKFLOW_TEMPLATE_DISPLAY_SPECS.map((spec) => (0, catalog_1.translate)(locale, spec.showKey, {
            value: (0, workflow_template_labels_1.resolveWorkflowTemplateLabelValue)(viewModel.workflowTemplateLabelsBySurface, spec.surface, locale),
        })),
        (0, catalog_1.translate)(locale, "issue.command.show.followupProposalPolicy", {
            value: viewModel.followupProposalPolicy ?? "off",
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.followupProposalApproval", {
            value: viewModel.followupProposalApproval ?? "auto",
        }),
        (0, catalog_1.translate)(locale, "issue.command.report.item.updated", {
            updatedAt: viewModel.updatedAtLabel,
        }),
        ...((viewModel.completedAtLabel ?? null) !== null
            ? [
                (0, catalog_1.translate)(locale, "issue.command.show.completed", {
                    value: viewModel.completedAtLabel ?? "",
                }),
            ]
            : []),
        (0, catalog_1.translate)(locale, "issue.command.show.workflowStatus", {
            value: viewModel.workflowStatusLabel,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.ruleLabels", {
            value: viewModel.ruleLabelsLabel,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.relatedPr", {
            value: (0, format_1.formatRelatedPullRequestText)(viewModel.pr),
        }),
        ...(0, pull_request_details_1.renderTextPullRequestDetails)(viewModel, locale),
        ...(viewModel.activeOverrideDetails.length > 0
            ? [
                (0, catalog_1.translate)(locale, "issue.command.show.activeOverrides", {
                    value: viewModel.activeOverrideDetails.join(" | "),
                }),
            ]
            : []),
        "",
        `${(0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowStateHeading")}:`,
        ...renderTextCanonicalWorkflowState(viewModel.issue.isOpen, viewModel.issue.workflowState, viewModel.canonicalWorkflowState, locale),
        ...(0, origins_1.renderOptionalTextOriginIssues)(viewModel, locale),
        ...renderOptionalTextChildIssues(viewModel, locale),
        ...(0, comments_1.renderOptionalTextPostCompletionComments)(viewModel, locale, displayTimeZone),
        "",
        `${viewModel.latestUpdateHeadingLabel}:`,
        ...renderTextLatestUpdate(viewModel.latestUpdate, locale, displayTimeZone),
        "",
        `${(0, catalog_1.translate)(locale, "issue.command.show.bodyHeading")}:`,
        ...renderTextBody(viewModel.issue.body, locale),
        ...(0, comments_1.renderOptionalTextComments)(viewModel, locale, displayTimeZone),
    ];
    return lines.join("\n").trimEnd();
}
function renderOptionalMarkdownChildIssues(viewModel, locale) {
    if (viewModel.childIssues.groups.length === 0 &&
        !viewModel.childIssues.requested) {
        return [];
    }
    return [
        "",
        `**${(0, catalog_1.translate)(locale, "issue.command.show.childIssuesHeading")}**`,
        ...renderMarkdownChildIssues(viewModel.childIssues, locale),
    ];
}
function renderMarkdownChildIssues(childIssues, locale) {
    if (childIssues.groups.length === 0) {
        return [`- ${(0, catalog_1.translate)(locale, "issue.command.show.none")}`];
    }
    return [
        ...childIssues.groups.flatMap((group) => renderMarkdownChildIssueGroup(group, locale)),
        ...renderMarkdownHiddenChildIssueCount(childIssues.hiddenCount, locale),
    ];
}
function renderMarkdownChildIssueGroup(group, locale) {
    return [
        `- **${(0, catalog_1.translate)(locale, childIssueGroupLabelKey(group.kind))}**`,
        ...group.items.map((item) => `  - ${renderMarkdownChildIssueItem(item, locale)}`),
    ];
}
function renderMarkdownChildIssueItem(item, locale) {
    const segments = renderChildIssueItemSegments(item, types_1.ISSUE_REPORT_FORMATS.markdown, locale);
    const [issueRef = "", ...rest] = segments;
    return [issueRef, ...rest.map(format_1.escapeMarkdownText)].join(" | ");
}
function renderMarkdownHiddenChildIssueCount(hiddenCount, locale) {
    return hiddenCount === 0
        ? []
        : [
            `- ${(0, catalog_1.translate)(locale, "issue.command.show.childIssues.hidden", {
                count: hiddenCount,
            })}`,
        ];
}
function renderOptionalTextChildIssues(viewModel, locale) {
    if (viewModel.childIssues.groups.length === 0 &&
        !viewModel.childIssues.requested) {
        return [];
    }
    return [
        "",
        `${(0, catalog_1.translate)(locale, "issue.command.show.childIssuesHeading")}:`,
        ...renderTextChildIssues(viewModel.childIssues, locale),
    ];
}
function renderTextChildIssues(childIssues, locale) {
    if (childIssues.groups.length === 0) {
        return [(0, catalog_1.translate)(locale, "issue.command.show.none")];
    }
    return [
        ...childIssues.groups.flatMap((group) => renderTextChildIssueGroup(group, locale)),
        ...renderTextHiddenChildIssueCount(childIssues.hiddenCount, locale),
    ];
}
function renderTextChildIssueGroup(group, locale) {
    return [
        `${(0, catalog_1.translate)(locale, childIssueGroupLabelKey(group.kind))}:`,
        ...group.items.map((item) => `- ${renderTextChildIssueItem(item, locale)}`),
    ];
}
function renderTextChildIssueItem(item, locale) {
    return renderChildIssueItemSegments(item, types_1.ISSUE_REPORT_FORMATS.text, locale).join(" | ");
}
function renderTextHiddenChildIssueCount(hiddenCount, locale) {
    return hiddenCount === 0
        ? []
        : [
            (0, catalog_1.translate)(locale, "issue.command.show.childIssues.hidden", {
                count: hiddenCount,
            }),
        ];
}
function renderChildIssueItemSegments(item, format, locale) {
    return [
        (0, format_1.formatIssueReference)(item.displayId, item.url, format),
        (0, catalog_1.translate)(locale, childIssueStateLabelKey(item.state)),
        ...(item.depth !== undefined && item.depth > 1
            ? [
                (0, catalog_1.translate)(locale, "issue.command.show.childIssues.depth", {
                    value: item.depth,
                }),
            ]
            : []),
        item.title,
        ...(item.summary !== null
            ? [
                (0, catalog_1.translate)(locale, "issue.command.show.childIssues.summary", {
                    value: item.summary,
                }),
            ]
            : []),
    ];
}
function childIssueGroupLabelKey(kind) {
    switch (kind) {
        case "controller":
            return "issue.command.show.childIssues.controller";
        case "unplanned":
            return "issue.command.show.childIssues.unplanned";
        case "recurring":
            return "issue.command.show.childIssues.recurring";
        case "followup":
            return "issue.command.show.childIssues.followup";
        case "support":
            return "issue.command.show.childIssues.support";
    }
}
function childIssueStateLabelKey(state) {
    switch (state) {
        case "open":
            return "issue.command.show.childIssues.state.open";
        case "closed":
            return "issue.command.show.childIssues.state.closed";
        case "pending":
            return "issue.command.show.childIssues.state.pending";
        case "unknown":
            return "issue.command.show.childIssues.state.unknown";
    }
}
function renderMarkdownLatestUpdate(latestUpdate, locale, displayTimeZone) {
    if (!latestUpdate) {
        return [`- ${(0, catalog_1.translate)(locale, "issue.command.show.none")}`];
    }
    return [
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.outcome", {
            value: (0, format_1.escapeMarkdownText)((0, publisher_events_1.renderWorkerOutcomeValue)(latestUpdate.parsed.workerOutcome ?? "proceed", locale, latestUpdate.parsed.terminalSuccess === true)),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.consecutiveAiRuns", {
            value: latestUpdate.parsed.consecutiveAiRuns,
        })}`,
        ...renderMarkdownLatestUpdateRunHours(latestUpdate, locale),
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.summary", {
            value: (0, format_1.escapeMarkdownText)(latestUpdate.parsed.summary),
        })}`,
        ...(latestUpdate.parsed.needsHumanReason
            ? [
                `- ${(0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.needsHumanReason", {
                    value: (0, format_1.escapeMarkdownText)((0, publisher_events_1.renderWorkflowNeedsHumanReasonValue)(latestUpdate.parsed.needsHumanReason, locale)),
                })}`,
            ]
            : []),
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.next", {
            value: (0, format_1.escapeMarkdownText)(latestUpdate.parsed.next),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.comment", {
            value: `${(0, format_1.formatIssueReference)(latestUpdate.comment.url, latestUpdate.comment.url, types_1.ISSUE_REPORT_FORMATS.markdown)} | ${(0, format_1.escapeMarkdownText)(latestUpdate.comment.author)} | ${(0, issue_report_1.formatIssueUpdatedAt)(resolveDisplayedCommentTimestamp(latestUpdate.comment), locale, displayTimeZone)}`,
        })}`,
    ];
}
function renderTextLatestUpdate(latestUpdate, locale, displayTimeZone) {
    if (!latestUpdate) {
        return [(0, catalog_1.translate)(locale, "issue.command.show.none")];
    }
    return [
        (0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.outcome", {
            value: (0, publisher_events_1.renderWorkerOutcomeValue)(latestUpdate.parsed.workerOutcome ?? "proceed", locale, latestUpdate.parsed.terminalSuccess === true),
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.consecutiveAiRuns", {
            value: latestUpdate.parsed.consecutiveAiRuns,
        }),
        ...renderTextLatestUpdateRunHours(latestUpdate, locale),
        (0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.summary", {
            value: latestUpdate.parsed.summary,
        }),
        ...(latestUpdate.parsed.needsHumanReason
            ? [
                (0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.needsHumanReason", {
                    value: (0, publisher_events_1.renderWorkflowNeedsHumanReasonValue)(latestUpdate.parsed.needsHumanReason, locale),
                }),
            ]
            : []),
        (0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.next", {
            value: latestUpdate.parsed.next,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.comment", {
            value: `${latestUpdate.comment.url} | ${latestUpdate.comment.author} | ${(0, issue_report_1.formatIssueUpdatedAt)(resolveDisplayedCommentTimestamp(latestUpdate.comment), locale, displayTimeZone)}`,
        }),
    ];
}
function renderMarkdownLatestUpdateRunHours(latestUpdate, locale) {
    if (latestUpdate.parsed.totalAiRunDuration === undefined) {
        return [];
    }
    return [
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.totalAiRunHours", {
            value: latestUpdate.parsed.totalAiRunDuration,
        })}`,
    ];
}
function renderTextLatestUpdateRunHours(latestUpdate, locale) {
    if (latestUpdate.parsed.totalAiRunDuration === undefined) {
        return [];
    }
    return [
        (0, catalog_1.translate)(locale, "issue.command.show.latestUpdate.totalAiRunHours", {
            value: latestUpdate.parsed.totalAiRunDuration,
        }),
    ];
}
function renderMarkdownCanonicalWorkflowState(issueIsOpen, workflowState, canonicalWorkflowState, locale) {
    if (!canonicalWorkflowState) {
        return [`- ${(0, catalog_1.translate)(locale, "issue.command.show.none")}`];
    }
    const { displaySummary, whyStuck } = resolveCanonicalWorkflowDisplayState({
        issueIsOpen,
        workflowState,
        canonicalWorkflowState,
    });
    return [
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowState.summary", {
            value: (0, format_1.escapeMarkdownText)(displaySummary),
        })}`,
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowState.next", {
            value: (0, format_1.escapeMarkdownText)(resolveCanonicalWorkflowNext(canonicalWorkflowState, locale)),
        })}`,
        ...(whyStuck !== null
            ? [
                `- ${(0, catalog_1.translate)(locale, "issue.command.report.item.whyStuck", {
                    value: (0, format_1.escapeMarkdownText)(whyStuck),
                })}`,
            ]
            : []),
        `- ${(0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowState.comment", {
            value: (0, format_1.formatIssueReference)(canonicalWorkflowState.commentUrl, canonicalWorkflowState.commentUrl, types_1.ISSUE_REPORT_FORMATS.markdown),
        })}`,
    ];
}
function renderTextCanonicalWorkflowState(issueIsOpen, workflowState, canonicalWorkflowState, locale) {
    if (!canonicalWorkflowState) {
        return [(0, catalog_1.translate)(locale, "issue.command.show.none")];
    }
    const { displaySummary, whyStuck } = resolveCanonicalWorkflowDisplayState({
        issueIsOpen,
        workflowState,
        canonicalWorkflowState,
    });
    return [
        (0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowState.summary", {
            value: displaySummary,
        }),
        (0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowState.next", {
            value: resolveCanonicalWorkflowNext(canonicalWorkflowState, locale),
        }),
        ...(whyStuck !== null
            ? [
                (0, catalog_1.translate)(locale, "issue.command.report.item.whyStuck", {
                    value: whyStuck,
                }),
            ]
            : []),
        (0, catalog_1.translate)(locale, "issue.command.show.canonicalWorkflowState.comment", {
            value: canonicalWorkflowState.commentUrl,
        }),
    ];
}
function resolveCanonicalWorkflowNext(canonicalWorkflowState, locale) {
    if ((0, auto_merge_state_1.hasActiveAutoMergeState)(canonicalWorkflowState)) {
        return (0, catalog_1.translate)(locale, "run.presentation.autoMergePendingNext");
    }
    return canonicalWorkflowState.next;
}
function resolveDisplayedCommentTimestamp(comment) {
    return comment.updatedAt ?? comment.createdAt;
}
function resolveCanonicalWorkflowDisplayState(input) {
    const displaySummary = input.workflowState === null
        ? input.canonicalWorkflowState.summary ||
            input.canonicalWorkflowState.resultSummary ||
            ""
        : ((0, issue_report_1.resolveCanonicalDisplaySummary)({
            isOpen: input.issueIsOpen,
            workflowStatus: input.workflowState.status,
            summary: input.canonicalWorkflowState.summary,
            resultSummary: input.canonicalWorkflowState.resultSummary,
        }) ?? input.canonicalWorkflowState.summary);
    return {
        displaySummary,
        whyStuck: input.workflowState === null ||
            displaySummary === input.canonicalWorkflowState.summary
            ? null
            : displaySummary,
    };
}
function renderMarkdownBody(body, locale) {
    if (body.trim().length === 0) {
        return [`- ${(0, catalog_1.translate)(locale, "issue.command.show.empty")}`];
    }
    return (0, format_1.toMarkdownCodeBlock)(body);
}
function renderTextBody(body, locale) {
    if (body.trim().length === 0) {
        return [(0, catalog_1.translate)(locale, "issue.command.show.empty")];
    }
    return body.split("\n");
}
