"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildIssueReportContext = buildIssueReportContext;
exports.buildInvalidCanonicalWorkflowStateView = buildInvalidCanonicalWorkflowStateView;
exports.buildIssueReportDerivedFields = buildIssueReportDerivedFields;
exports.formatActiveOverrideDetails = formatActiveOverrideDetails;
exports.formatCommentExcerpt = formatCommentExcerpt;
exports.formatIssueUpdatedAt = formatIssueUpdatedAt;
exports.resolveCanonicalDisplaySummary = resolveCanonicalDisplaySummary;
exports.getIssueReportBucket = getIssueReportBucket;
exports.formatPendingDependencySyncLabel = formatPendingDependencySyncLabel;
exports.formatDependencySyncHistoryLabel = formatDependencySyncHistoryLabel;
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 display_time_1 = require("../i18n/display-time");
const types_1 = require("../platform/workflow-state/types");
const workflow_timeline_scan_1 = require("../workflows/workflow-timeline-scan");
const config_override_display_1 = require("../workflows/config-override-display");
const display_labels_1 = require("../workflows/display-labels");
const optional_text_1 = require("../workflows/optional-text");
const publisher_events_1 = require("../workflows/publisher-events");
const auto_merge_state_1 = require("../workflows/auto-merge-state");
const recurring_1 = require("../workflows/recurring");
const scheduled_run_1 = require("../workflows/scheduled-run");
const COMMENT_LIMIT = 120;
const ACTIONABLE_COMMENT_LIMIT = 2;
function buildIssueReportContext(issue, comments, pr, trackerBlockingDependencies) {
    let latestUpdate = null;
    for (const comment of comments) {
        const parsed = (0, workflow_update_1.parseWorkflowUpdate)(comment.body);
        if (parsed) {
            latestUpdate = parsed;
        }
    }
    const recentActionableComments = comments
        .filter(workflow_timeline_scan_1.isActionableWorkflowComment)
        .slice(-ACTIONABLE_COMMENT_LIMIT);
    const canonicalResolution = (0, canonical_workflow_state_1.resolveCanonicalWorkflowStateComment)(comments);
    let canonicalWorkflowState = null;
    if (canonicalResolution.kind === "found") {
        const canonicalStateSummary = (0, canonical_workflow_state_1.summarizeCanonicalWorkflowState)(canonicalResolution.workflowState, catalog_1.DEFAULT_APP_LOCALE, "UTC", issue.id);
        canonicalWorkflowState = {
            summary: canonicalStateSummary.currentStep,
            next: canonicalStateSummary.next,
            workflowSurface: canonicalResolution.workflowState.workflowSurface,
            workflowTemplates: canonicalResolution.workflowState.workflowTemplates,
            followupProposalPolicy: canonicalResolution.workflowState.followup?.proposalPolicy ?? "off",
            followupProposalApproval: canonicalResolution.workflowState.followup?.proposalApproval ?? "auto",
            commentUrl: canonicalResolution.comment.url,
            resultSummary: canonicalStateSummary.resultSummary,
            configOverrides: canonicalResolution.workflowState.configOverrides ?? null,
            ...(canonicalResolution.workflowState.autoMergeState !== undefined
                ? { autoMergeState: canonicalResolution.workflowState.autoMergeState }
                : {}),
            isRecurringParent: (0, recurring_1.isRecurringParentWorkflowState)(canonicalResolution.workflowState),
            hasActiveScheduledRun: (0, scheduled_run_1.hasActiveScheduledRun)(canonicalResolution.workflowState),
            pendingDependencySyncLabel: formatPendingDependencySyncLabel(canonicalResolution.workflowState.dependencySyncState),
            dependencySyncHistoryLabel: formatDependencySyncHistoryLabel(canonicalResolution.workflowState.dependencySyncState),
        };
    }
    else if (canonicalResolution.kind === "invalid") {
        canonicalWorkflowState = buildInvalidCanonicalWorkflowStateView({
            summary: canonicalResolution.summary,
            comment: canonicalResolution.comment,
        });
    }
    return {
        issue,
        pr,
        openBlockingDependencies: trackerBlockingDependencies.filter((dependency) => dependency.isOpen),
        latestUpdate,
        canonicalWorkflowState,
        recentActionableComments,
    };
}
function buildInvalidCanonicalWorkflowStateView(input) {
    const locale = input.locale ?? catalog_1.DEFAULT_APP_LOCALE;
    return {
        summary: input.summary,
        next: (0, catalog_1.translate)(locale, "run.presentation.failNext"),
        workflowSurface: null,
        workflowTemplates: null,
        followupProposalPolicy: "off",
        followupProposalApproval: "auto",
        commentUrl: input.comment.url,
        resultSummary: null,
        configOverrides: null,
        isRecurringParent: false,
        hasActiveScheduledRun: false,
        pendingDependencySyncLabel: "-",
        dependencySyncHistoryLabel: "-",
    };
}
function buildIssueReportDerivedFields(context, locale = catalog_1.DEFAULT_APP_LOCALE, displayTimeZone = "UTC", workflowDisplayCatalog = null) {
    const latestActionableComment = context.recentActionableComments[context.recentActionableComments.length - 1] ?? null;
    const latestUpdateSummary = context.latestUpdate?.summary?.trim();
    const latestUpdateNext = context.latestUpdate?.next?.trim();
    const canonicalSummary = context.canonicalWorkflowState?.summary?.trim();
    const canonicalNext = context.canonicalWorkflowState?.next?.trim();
    const canonicalResultSummary = context.canonicalWorkflowState?.resultSummary?.trim() ?? null;
    const canonicalDisplaySummary = resolveCanonicalDisplaySummary({
        isOpen: context.issue.isOpen,
        workflowStatus: context.issue.workflowState.status,
        summary: canonicalSummary,
        resultSummary: canonicalResultSummary,
    });
    const hasAutoMergeState = (0, auto_merge_state_1.hasActiveAutoMergeState)(context.canonicalWorkflowState);
    const fallbackAutoMergeNext = hasAutoMergeState
        ? (0, catalog_1.translate)(locale, "run.presentation.autoMergePendingNext")
        : null;
    const autoMergeNext = fallbackAutoMergeNext !== null &&
        context.latestUpdate?.event === publisher_events_1.WORKFLOW_VISIBLE_EVENTS.autoMergePending &&
        latestUpdateNext
        ? latestUpdateNext
        : fallbackAutoMergeNext;
    const latestActionableCommentExcerpt = latestActionableComment
        ? formatCommentExcerpt(latestActionableComment)
        : null;
    const blockingLabel = formatOpenBlockingDependencies(context.openBlockingDependencies);
    const activeOverrideDetails = formatActiveOverrideDetails(context.canonicalWorkflowState?.configOverrides ?? null);
    return {
        bucket: getIssueReportBucket(context.issue.workflowState),
        hasAiDisabled: context.issue.workflowState.rules.includes(types_1.WORKFLOW_RULES.aiDisabled),
        updatedAtLabel: formatIssueUpdatedAt(context.issue.updatedAt, locale, displayTimeZone),
        ...(0, display_labels_1.resolveWorkflowDisplayLabels)({
            catalog: workflowDisplayCatalog,
            activeSurface: context.canonicalWorkflowState?.workflowSurface,
            workflowTemplates: context.canonicalWorkflowState?.workflowTemplates,
        }),
        followupProposalPolicy: context.canonicalWorkflowState?.followupProposalPolicy ?? "off",
        followupProposalApproval: context.canonicalWorkflowState?.followupProposalApproval ?? "auto",
        latestUpdateNeedsHumanReason: context.issue.workflowState.status === "ai-needs-human" &&
            context.latestUpdate?.needsHumanReason
            ? (0, publisher_events_1.renderWorkflowNeedsHumanReasonValue)(context.latestUpdate.needsHumanReason, locale)
            : null,
        canonicalWorkflowSummary: canonicalDisplaySummary,
        canonicalWorkflowNext: autoMergeNext ?? canonicalNext ?? null,
        canonicalWorkflowCommentUrl: context.canonicalWorkflowState?.commentUrl ?? null,
        isRecurringParent: context.canonicalWorkflowState?.isRecurringParent ?? false,
        hasActiveScheduledRun: context.canonicalWorkflowState?.hasActiveScheduledRun ?? false,
        blockingLabel,
        hasActiveAutoMergeState: hasAutoMergeState,
        pendingDependencySyncLabel: context.canonicalWorkflowState?.pendingDependencySyncLabel ?? "-",
        dependencySyncHistoryLabel: context.canonicalWorkflowState?.dependencySyncHistoryLabel ?? "-",
        whyStuck: pickFirstText(canonicalDisplaySummary, latestUpdateSummary, latestActionableCommentExcerpt),
        nextAction: pickFirstText(autoMergeNext, canonicalNext, latestUpdateNext),
        activeOverridesSummary: activeOverrideDetails.length > 0
            ? activeOverrideDetails.join("; ")
            : null,
        activeOverrideDetails,
    };
}
function formatActiveOverrideDetails(patch) {
    return (0, config_override_display_1.formatConfigOverrideDisplayEntries)(patch);
}
function formatCommentExcerpt(comment) {
    const normalized = comment.body.trim().replace(/\s+/g, " ");
    if (normalized.length <= COMMENT_LIMIT) {
        return normalized;
    }
    return `${normalized.slice(0, COMMENT_LIMIT)}...`;
}
function formatIssueUpdatedAt(updatedAt, locale = catalog_1.DEFAULT_APP_LOCALE, displayTimeZone = "UTC") {
    return (0, display_time_1.formatHumanTimestamp)(updatedAt, locale, displayTimeZone);
}
function resolveCanonicalDisplaySummary(input) {
    const summary = (0, optional_text_1.normalizeOptionalText)(input.summary);
    const resultSummary = (0, optional_text_1.normalizeOptionalText)(input.resultSummary);
    if (summary === null && resultSummary === null) {
        return null;
    }
    return shouldPreferCanonicalResultSummary({
        isOpen: input.isOpen,
        workflowStatus: input.workflowStatus,
        resultSummary,
    })
        ? pickFirstText(resultSummary, summary)
        : pickFirstText(summary, resultSummary);
}
function getIssueReportBucket(workflowState) {
    if (workflowState.rules.includes(types_1.WORKFLOW_RULES.aiDisabled)) {
        return "ai-disabled";
    }
    return workflowState.status;
}
function pickFirstText(...values) {
    for (const value of values) {
        if (value === undefined || value === null) {
            continue;
        }
        const normalized = value.trim();
        if (normalized.length > 0) {
            return normalized;
        }
    }
    return "-";
}
function shouldPreferCanonicalResultSummary(input) {
    if (input.resultSummary === null) {
        return false;
    }
    if (!input.isOpen) {
        return true;
    }
    return input.workflowStatus === types_1.WORKFLOW_STATUSES.aiNeedsHuman;
}
function formatOpenBlockingDependencies(dependencies) {
    if (dependencies.length === 0) {
        return "-";
    }
    return dependencies.map((dependency) => dependency.displayId).join(", ");
}
function formatPendingDependencySyncLabel(dependencySyncState) {
    const pendingIssueDisplayIds = [
        ...new Set((dependencySyncState?.managedDependencies ?? [])
            .filter((dependency) => dependency.completionRequeuedAt === null)
            .map((dependency) => formatManagedDependencyIssueDisplayId(dependency.issueId))),
    ];
    if (pendingIssueDisplayIds.length === 0) {
        return "-";
    }
    return pendingIssueDisplayIds.join(", ");
}
function formatDependencySyncHistoryLabel(dependencySyncState) {
    const outcomes = [
        ...new Set((dependencySyncState?.managedDependencies ?? [])
            .filter((dependency) => dependency.completionRequeuedAt !== null)
            .map((dependency) => `${formatManagedDependencyIssueDisplayId(dependency.issueId)} (requeued)`)),
    ];
    if (outcomes.length === 0) {
        return "-";
    }
    return outcomes.join(", ");
}
function formatManagedDependencyIssueDisplayId(issueId) {
    return issueId.startsWith("#") ? issueId : `#${issueId}`;
}
