"use strict";
/**
 * Pasted text detection + Enter resend helper
 *
 * Shared helper for claude-session.ts and codex.ts to detect
 * [Pasted text #N +XX lines] in tmux output and automatically
 * resend Enter to start processing.
 *
 * @see Issue #212
 * @designNote SF-001: Extracted as common helper to eliminate code duplication
 *   between claude-session.ts and codex.ts.
 * @designNote MF-S4-001: sessionName is expected to be generated by
 *   getSessionName() in fixed format ('mcbd-{cli}-{worktreeId}').
 *   tmux.ts provides double-quote escaping as a defense layer.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectAndResendIfPastedText = detectAndResendIfPastedText;
const tmux_1 = require("./tmux/tmux");
const cli_patterns_1 = require("./detection/cli-patterns");
const logger_1 = require("./logger");
// SF-S2-002: Logger is generated internally, not injected from callers
const logger = (0, logger_1.createLogger)('pasted-text');
/**
 * Detect [Pasted text] in tmux buffer and resend Enter if found.
 *
 * Called after sending a multi-line message to handle Claude CLI's
 * paste detection behavior. The caller is responsible for the
 * message.includes('\n') guard condition.
 *
 * @param sessionName - tmux session name, generated by getSessionName()
 * @returns Promise<void>
 *
 * @designNote PASTE-HELPER: Caller responsibilities vs helper responsibilities:
 *   Caller: message.includes('\n') guard + call timing control
 *   Helper: detect loop (setTimeout wait -> capturePane -> test -> Enter resend)
 * @designNote SF-S2-005: Uses setTimeout+Promise pattern (project convention)
 */
async function detectAndResendIfPastedText(sessionName) {
    for (let attempt = 0; attempt < cli_patterns_1.MAX_PASTED_TEXT_RETRIES; attempt++) {
        // SF-S2-005: Project-standard delay pattern
        await new Promise(resolve => setTimeout(resolve, cli_patterns_1.PASTED_TEXT_DETECT_DELAY));
        // PASTE-002: Read only last 10 lines -- [Pasted text] appears in recent output
        const output = await (0, tmux_1.capturePane)(sessionName, { startLine: -10 });
        if (!cli_patterns_1.PASTED_TEXT_PATTERN.test((0, cli_patterns_1.stripAnsi)(output))) {
            return; // Normal: no Pasted text detected
        }
        // Pasted text detected -- resend Enter
        await (0, tmux_1.sendKeys)(sessionName, '', true);
        if (attempt === cli_patterns_1.MAX_PASTED_TEXT_RETRIES - 1) {
            // SF-S4-001: Log with attempt count for traceability
            logger.warn('Pasted text detection: max retries reached', {
                sessionName,
                maxRetries: cli_patterns_1.MAX_PASTED_TEXT_RETRIES,
                finalAttempt: attempt,
            });
        }
    }
}
