"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderEmptyIssueReport = renderEmptyIssueReport;
exports.renderIssueReport = renderIssueReport;
const catalog_1 = require("../../i18n/catalog");
const issue_report_1 = require("../../issues/issue-report");
const types_1 = require("../../issues/types");
const format_1 = require("./format");
const types_2 = require("./types");
const workflow_template_labels_1 = require("./workflow-template-labels");
const MARKDOWN_ISSUE_BUCKET_ORDER = [
    "ai-needs-human",
    ...types_2.WORKFLOW_BUCKET_ORDER.filter((bucket) => bucket !== "ai-needs-human"),
];
const MARKDOWN_SUMMARY_ROWS = [
    "needsHuman",
    "active",
    "recurring",
    "scheduled",
];
function renderEmptyIssueReport(options, locale = catalog_1.DEFAULT_APP_LOCALE) {
    return `${(0, catalog_1.translate)(locale, "issue.command.report.empty")}${(0, format_1.renderFilterSuffix)(options)}`;
}
function renderIssueReport(items, workflowLabels, options, locale = catalog_1.DEFAULT_APP_LOCALE, displayTimeZone = "UTC", workflowDisplayCatalog = null) {
    const viewModel = buildIssueReportViewModel(items, workflowLabels, locale, displayTimeZone, workflowDisplayCatalog);
    return options.format === types_1.ISSUE_REPORT_FORMATS.markdown
        ? renderMarkdownIssueReport(viewModel, items.length, options, locale)
        : renderTextIssueReport(viewModel, items.length, workflowLabels, options, locale);
}
function buildIssueReportViewModel(items, workflowLabels, locale, displayTimeZone, workflowDisplayCatalog) {
    const summary = {
        open: 0,
        aiReady: 0,
        aiRunning: 0,
        aiNeedsHuman: 0,
        aiWorkingInPr: 0,
        aiRecurring: 0,
        aiScheduled: 0,
        aiDisabled: 0,
    };
    const buckets = {
        "ai-ready": [],
        "ai-running": [],
        "ai-needs-human": [],
        "ai-working-in-pr": [],
        "ai-recurring": [],
        "ai-scheduled": [],
        "ai-disabled": [],
    };
    for (const context of items) {
        const item = buildIssueListItem(context, workflowLabels, locale, displayTimeZone, workflowDisplayCatalog);
        summary.open += context.issue.isOpen ? 1 : 0;
        switch (item.bucket) {
            case "ai-ready":
                summary.aiReady += 1;
                break;
            case "ai-running":
                summary.aiRunning += 1;
                break;
            case "ai-needs-human":
                summary.aiNeedsHuman += 1;
                break;
            case "ai-working-in-pr":
                summary.aiWorkingInPr += 1;
                break;
            case "ai-recurring":
                summary.aiRecurring += 1;
                break;
            case "ai-scheduled":
                summary.aiScheduled += 1;
                break;
            case "ai-disabled":
                summary.aiDisabled += 1;
                break;
        }
        buckets[item.bucket].push(item);
    }
    return { summary, buckets };
}
function buildIssueListItem(context, workflowLabels, locale, displayTimeZone, workflowDisplayCatalog) {
    const derived = (0, issue_report_1.buildIssueReportDerivedFields)(context, locale, displayTimeZone, workflowDisplayCatalog);
    return {
        bucket: derived.bucket,
        displayId: context.issue.displayId,
        title: context.issue.title,
        stateLabel: (0, format_1.formatWorkflowState)(derived.bucket, workflowLabels),
        updatedAtLabel: derived.updatedAtLabel,
        workflowTemplateLabel: derived.workflowTemplateLabel,
        workflowTemplateLabelsBySurface: derived.workflowTemplateLabelsBySurface,
        followupProposalPolicy: derived.followupProposalPolicy,
        followupProposalApproval: derived.followupProposalApproval,
        issueUrl: context.issue.url,
        prDisplayId: (0, format_1.formatPullRequestDisplayId)(context.pr),
        prUrl: context.pr?.url ?? null,
        assigneeCount: context.issue.assignees.length,
        assigneesLabel: (0, format_1.formatAssignees)(context.issue.assignees),
        canonicalWorkflowSummary: derived.canonicalWorkflowSummary,
        canonicalWorkflowCommentUrl: derived.canonicalWorkflowCommentUrl,
        isRecurringParent: derived.isRecurringParent,
        hasActiveScheduledRun: derived.hasActiveScheduledRun,
        blockingLabel: derived.blockingLabel,
        hasActiveAutoMergeState: derived.hasActiveAutoMergeState,
        pendingDependencySyncLabel: derived.pendingDependencySyncLabel,
        dependencySyncHistoryLabel: derived.dependencySyncHistoryLabel,
        whyStuck: derived.whyStuck,
        nextAction: derived.nextAction,
        needsHumanReason: derived.latestUpdateNeedsHumanReason,
        activeOverridesSummary: derived.activeOverridesSummary,
        activeOverrideDetails: derived.activeOverrideDetails,
    };
}
function renderTextIssueReport(viewModel, count, workflowLabels, options, locale) {
    const lines = [
        `${(0, catalog_1.translate)(locale, "issue.command.report.title", {
            count,
        })}${(0, format_1.renderFilterSuffix)(options)}`,
        (0, format_1.formatSummaryLine)(viewModel.summary, workflowLabels, locale),
        "",
    ];
    for (const bucket of types_2.WORKFLOW_BUCKET_ORDER) {
        const bucketItems = viewModel.buckets[bucket];
        if (bucketItems.length === 0) {
            continue;
        }
        lines.push(`${(0, format_1.formatBucketLabel)(bucket, workflowLabels)} (${bucketItems.length})`);
        for (const [index, item] of bucketItems.entries()) {
            lines.push(...renderTextIssueItem(item, index + 1, options.view, locale));
        }
        lines.push("");
    }
    return lines.join("\n").trimEnd();
}
function renderMarkdownIssueReport(viewModel, count, options, locale) {
    const items = flattenMarkdownIssueItems(viewModel);
    const lines = [
        (0, catalog_1.translate)(locale, "issue.command.report.markdownTitle", {
            count,
        }),
        "",
        `**${formatMarkdownCriteria(options, count, locale)}**`,
        "",
        (0, catalog_1.translate)(locale, "issue.command.report.markdown.summaryHeading"),
        "",
        ...renderMarkdownSummaryTable(items, locale),
        "",
        (0, catalog_1.translate)(locale, "issue.command.report.markdown.issueListHeading"),
        "",
        ...renderMarkdownIssueTable(items, locale),
    ];
    return lines.join("\n").trimEnd();
}
function flattenMarkdownIssueItems(viewModel) {
    return MARKDOWN_ISSUE_BUCKET_ORDER.flatMap((bucket) => viewModel.buckets[bucket]);
}
function formatMarkdownCriteria(options, count, locale) {
    return [
        (0, catalog_1.translate)(locale, `issue.command.report.criteria.state.${options.state ?? types_2.DEFAULT_ISSUE_STATE}`),
        options.days === undefined
            ? (0, catalog_1.translate)(locale, "issue.command.report.criteria.days.all")
            : (0, catalog_1.translate)(locale, "issue.command.report.criteria.days.recent", {
                days: options.days,
            }),
        options.labels && options.labels.length > 0
            ? (0, catalog_1.translate)(locale, "issue.command.report.criteria.labels", {
                labels: (0, format_1.escapeMarkdownText)(options.labels.join(",")),
            })
            : (0, catalog_1.translate)(locale, "issue.command.report.criteria.labels.none"),
        ...(options.assignees && options.assignees.length > 0
            ? [
                (0, catalog_1.translate)(locale, "issue.command.report.criteria.assignees", {
                    assignees: (0, format_1.escapeMarkdownText)(options.assignees.join(",")),
                }),
            ]
            : []),
        ...(options.limit !== undefined
            ? [
                (0, catalog_1.translate)(locale, "issue.command.report.criteria.limit", {
                    limit: options.limit,
                }),
            ]
            : []),
        (0, catalog_1.translate)(locale, "issue.command.report.criteria.count", {
            count,
        }),
    ].join(" / ");
}
function renderMarkdownSummaryTable(items, locale) {
    const rows = buildMarkdownSummaryRows(items);
    return [
        `| ${(0, catalog_1.translate)(locale, "issue.command.report.markdown.column.category")} | ${(0, catalog_1.translate)(locale, "issue.command.report.markdown.column.count")} | ${(0, catalog_1.translate)(locale, "issue.command.report.markdown.column.issuePr")} |`,
        "|---|---:|---|",
        ...rows
            .map((row) => [
            (0, catalog_1.translate)(locale, `issue.command.report.markdown.summary.${row.key}`),
            String(row.items.length),
            formatMarkdownSummaryIssueReferences(row.items),
        ].join(" | "))
            .map((row) => `| ${row} |`),
    ];
}
function buildMarkdownSummaryRows(items) {
    const itemsByRow = new Map(MARKDOWN_SUMMARY_ROWS.map((key) => [key, []]));
    for (const item of items) {
        const key = resolveMarkdownSummaryRowKey(item);
        if (key === null) {
            continue;
        }
        itemsByRow.get(key)?.push(item);
    }
    return MARKDOWN_SUMMARY_ROWS.map((key) => ({
        key,
        items: itemsByRow.get(key) ?? [],
    }));
}
function resolveMarkdownSummaryRowKey(item) {
    if (item.bucket === "ai-needs-human") {
        return "needsHuman";
    }
    if (item.isRecurringParent || item.bucket === "ai-recurring") {
        return "recurring";
    }
    if (item.hasActiveScheduledRun || item.bucket === "ai-scheduled") {
        return "scheduled";
    }
    if (item.bucket === "ai-ready" ||
        item.bucket === "ai-running" ||
        item.bucket === "ai-working-in-pr") {
        return "active";
    }
    return null;
}
function formatMarkdownSummaryIssueReferences(items) {
    return items.length > 0
        ? items.map(formatMarkdownIssuePrSummaryReference).join(" ")
        : "-";
}
function renderMarkdownIssueTable(items, locale) {
    const showAssignees = shouldShowMarkdownAssignees(items);
    const headers = [
        (0, catalog_1.translate)(locale, "issue.command.report.markdown.column.issuePr"),
        (0, catalog_1.translate)(locale, "issue.command.report.markdown.column.status"),
        ...(showAssignees
            ? [(0, catalog_1.translate)(locale, "issue.command.report.markdown.column.assignees")]
            : []),
        (0, catalog_1.translate)(locale, "issue.command.report.markdown.column.actionRequired"),
        (0, catalog_1.translate)(locale, "issue.command.report.markdown.column.summary"),
        (0, catalog_1.translate)(locale, "issue.command.report.markdown.column.updated"),
    ];
    return [
        `| ${headers.join(" | ")} |`,
        `|${headers.map(() => "---").join("|")}|`,
        ...items
            .map((item) => [
            formatMarkdownIssuePrTitleReference(item),
            (0, format_1.escapeMarkdownText)(item.stateLabel),
            ...(showAssignees ? [(0, format_1.escapeMarkdownText)(item.assigneesLabel)] : []),
            formatMarkdownActionRequired(item, locale),
            (0, format_1.escapeMarkdownText)(item.whyStuck),
            (0, format_1.escapeMarkdownText)(item.updatedAtLabel),
        ].join(" | "))
            .map((row) => `| ${row} |`),
    ];
}
function shouldShowMarkdownAssignees(items) {
    return items.some((item) => item.assigneeCount > 1);
}
function formatMarkdownIssuePrSummaryReference(item) {
    const issueReference = (0, format_1.formatIssueReference)(item.displayId, item.issueUrl, types_1.ISSUE_REPORT_FORMATS.markdown);
    const prReference = formatMarkdownPullRequestReference(item);
    return prReference ? `${issueReference}(${prReference})` : issueReference;
}
function formatMarkdownIssuePrTitleReference(item) {
    return `${formatMarkdownIssuePrSummaryReference(item)} ${(0, format_1.escapeMarkdownTitle)(item.title)}`;
}
function formatMarkdownPullRequestReference(item) {
    return item.prDisplayId && item.prUrl
        ? (0, format_1.formatIssueReference)(item.prDisplayId, item.prUrl, types_1.ISSUE_REPORT_FORMATS.markdown)
        : null;
}
function formatMarkdownActionRequired(item, locale) {
    return item.bucket === "ai-needs-human"
        ? (0, catalog_1.translate)(locale, "issue.command.report.markdown.actionRequired")
        : "-";
}
function renderTextIssueItem(item, index, view, locale) {
    const lines = [
        `${index}. ${item.displayId} ${item.title} | ${item.stateLabel} | ${(0, catalog_1.translate)(locale, "issue.command.report.item.updated", {
            updatedAt: item.updatedAtLabel,
        })} | ${(0, format_1.formatTextPullRequest)(item, locale)}`,
        `   ${(0, catalog_1.translate)(locale, "issue.command.report.item.whyStuck", {
            value: item.whyStuck,
        })}`,
    ];
    if (view === "detailed") {
        lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.assignees", {
            value: item.assigneesLabel,
        })}`);
        if (item.blockingLabel !== "-") {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.blockedBy", {
                value: item.blockingLabel,
            })}`);
        }
        appendTextDependencyIntegrationLines(lines, item, locale, {
            includeOutcomes: true,
        });
        appendTextWorkflowTemplateLines(lines, item, locale);
        if (item.needsHumanReason) {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.needsHumanReason", {
                value: item.needsHumanReason,
            })}`);
        }
        if (item.activeOverrideDetails.length > 0) {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.activeOverrides", {
                value: item.activeOverrideDetails.join(" | "),
            })}`);
        }
        lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.nextAction", {
            value: item.nextAction,
        })}`);
        if (item.canonicalWorkflowSummary && item.canonicalWorkflowCommentUrl) {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.workflowState", {
                value: `${item.canonicalWorkflowSummary} | ${item.canonicalWorkflowCommentUrl}`,
            })}`);
        }
    }
    else {
        if (item.blockingLabel !== "-") {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.blockedBy", {
                value: item.blockingLabel,
            })}`);
        }
        appendTextDependencyIntegrationLines(lines, item, locale, {
            includeOutcomes: false,
        });
        if (item.needsHumanReason) {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.needsHumanReason", {
                value: item.needsHumanReason,
            })}`);
        }
        if (item.activeOverridesSummary) {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.activeOverrides", {
                value: item.activeOverridesSummary,
            })}`);
        }
        if (item.hasActiveAutoMergeState) {
            lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.nextAction", {
                value: item.nextAction,
            })}`);
        }
        appendTextWorkflowTemplateLines(lines, item, locale);
    }
    if (view === "compact" &&
        item.canonicalWorkflowSummary &&
        item.canonicalWorkflowCommentUrl) {
        lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.workflowState", {
            value: `${item.canonicalWorkflowSummary} | ${item.canonicalWorkflowCommentUrl}`,
        })}`);
    }
    return lines;
}
function appendTextWorkflowTemplateLines(lines, item, locale) {
    const noTemplate = (0, catalog_1.translate)(locale, "workflow.runContext.none");
    lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.workflow", {
        value: item.workflowTemplateLabel ?? noTemplate,
    })}`);
    for (const spec of workflow_template_labels_1.SIDE_WORKFLOW_TEMPLATE_DISPLAY_SPECS) {
        lines.push(`   ${(0, catalog_1.translate)(locale, spec.reportItemKey, {
            value: (0, workflow_template_labels_1.resolveWorkflowTemplateLabelValue)(item.workflowTemplateLabelsBySurface, spec.surface, locale),
        })}`);
    }
    lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.followupProposalPolicy", {
        value: item.followupProposalPolicy,
    })}`);
    lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.followupProposalApproval", {
        value: item.followupProposalApproval,
    })}`);
}
function appendTextDependencyIntegrationLines(lines, item, locale, options) {
    if (item.pendingDependencySyncLabel !== "-") {
        lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.pendingDependencySync", {
            value: item.pendingDependencySyncLabel,
        })}`);
    }
    if (options.includeOutcomes && item.dependencySyncHistoryLabel !== "-") {
        lines.push(`   ${(0, catalog_1.translate)(locale, "issue.command.report.item.dependencySyncHistory", {
            value: item.dependencySyncHistoryLabel,
        })}`);
    }
}
