/**
 * Retry mode for failed tasks.
 *
 * Provides a dedicated conversation loop with failure context,
 * run session data, and workflow structure injected into the system prompt.
 */
import { displayAndClearSessionState, runConversationLoop, } from './conversationLoop.js';
import { initializeSession } from './sessionInitialization.js';
import { createSelectActionWithoutExecute, buildSummaryActionOptions, formatStepPreviews, selectSummaryAction, } from './interactive-summary.js';
import { resolveLanguage } from './interactive.js';
import { buildInteractivePolicyPrompt } from './policyPrompt.js';
import { loadTemplate } from '../../shared/prompts/index.js';
import { getLabel, getLabelObject } from '../../shared/i18n/index.js';
import { resolveConfigValues } from '../../infra/config/index.js';
const RETRY_TOOLS = ['Read', 'Glob', 'Grep', 'Bash', 'WebSearch', 'WebFetch'];
function formatRetrySubjectLabel(kind, lang) {
    if (kind === 'run') {
        return 'Run';
    }
    return lang === 'ja' ? 'ブランチ' : 'Branch';
}
export function buildRetryTemplateVars(ctx, lang) {
    const hasWorkflowPreview = !!ctx.workflowContext.stepPreviews?.length;
    const stepDetails = hasWorkflowPreview && ctx.workflowContext.stepPreviews
        ? formatStepPreviews(ctx.workflowContext.stepPreviews, lang)
        : '';
    const run = ctx.run;
    const hasRun = run !== null;
    return {
        taskName: ctx.failure.taskName,
        taskContent: ctx.failure.taskContent,
        subjectLabel: formatRetrySubjectLabel(ctx.subject.kind, lang),
        subjectValue: ctx.subject.value,
        createdAt: ctx.failure.createdAt,
        failedStep: ctx.failure.failedStep,
        failureError: ctx.failure.error,
        failureLastMessage: ctx.failure.lastMessage,
        retryNote: ctx.failure.retryNote,
        hasWorkflowPreview: hasWorkflowPreview,
        workflowStructure: ctx.workflowContext.workflowStructure,
        stepDetails,
        hasRun,
        runLogsDir: run !== null ? run.logsDir : '',
        runReportsDir: run !== null ? run.reportsDir : '',
        runTask: run !== null ? run.task : '',
        runWorkflow: run !== null ? run.workflow : '',
        runStatus: run !== null ? run.status : '',
        runStepLogs: run !== null ? run.stepLogs : '',
        runReports: run !== null ? run.reports : '',
        hasOrderContent: ctx.previousOrderContent !== null,
        orderContent: ctx.previousOrderContent ?? '',
    };
}
function createDirectRetrySelectAction(ui) {
    return async (task) => selectSummaryAction(task, ui.proposed, ui.actionPrompt, buildSummaryActionOptions({
        execute: ui.actions.execute,
        saveTask: ui.actions.saveTask,
        continue: ui.actions.continue,
    }, [], ['save_task']));
}
async function runRetryConversation(cwd, retryContext, createSelectAction) {
    const globalConfig = resolveConfigValues(cwd, ['language', 'provider']);
    const lang = resolveLanguage(globalConfig.language);
    if (!globalConfig.provider) {
        throw new Error('Provider is not configured.');
    }
    const baseCtx = initializeSession(cwd, 'retry');
    const ctx = { ...baseCtx, lang, personaName: 'retry' };
    displayAndClearSessionState(cwd, ctx.lang);
    const ui = getLabelObject('instruct.ui', ctx.lang);
    const templateVars = buildRetryTemplateVars(retryContext, lang);
    const systemPrompt = loadTemplate('score_retry_system_prompt', ctx.lang, templateVars);
    const retryIntro = getLabel('retry.ui.intro', ctx.lang);
    const subjectLabel = formatRetrySubjectLabel(retryContext.subject.kind, ctx.lang);
    const introLabel = ctx.lang === 'ja'
        ? `## リトライ: ${retryContext.failure.taskName}\n\n${subjectLabel}: ${retryContext.subject.value}\n\n${retryIntro}`
        : `## Retry: ${retryContext.failure.taskName}\n\n${subjectLabel}: ${retryContext.subject.value}\n\n${retryIntro}`;
    const strategy = {
        systemPrompt,
        allowedTools: RETRY_TOOLS,
        transformPrompt: (userMessage, sourceContext) => buildInteractivePolicyPrompt(ctx.lang, userMessage, sourceContext),
        introMessage: introLabel,
        selectAction: createSelectAction(ui),
        previousOrderContent: retryContext.previousOrderContent ?? undefined,
        enableRetryCommand: true,
    };
    const result = await runConversationLoop(cwd, ctx, strategy, retryContext.workflowContext, undefined);
    if (result.action === 'cancel') {
        return {
            action: 'cancel',
            task: '',
            ...(result.attachments ? { attachments: result.attachments } : {}),
        };
    }
    return {
        action: result.action,
        task: result.task,
        ...(result.attachments ? { attachments: result.attachments } : {}),
    };
}
export async function runTaskRetryMode(cwd, retryContext) {
    return runRetryConversation(cwd, retryContext, createSelectActionWithoutExecute);
}
export async function runDirectRetryMode(cwd, retryContext) {
    return runRetryConversation(cwd, retryContext, createDirectRetrySelectAction);
}
//# sourceMappingURL=retryMode.js.map