import { readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { createInterface } from 'node:readline';
import { CliError } from '../../../../errors/cli-error.js';
import { ensureDir, fileExists } from '../../../../fs/io.js';
export const defaultTriageDependencies = {
    readJsonFile: async (path) => {
        const content = await readFile(path, 'utf8');
        return JSON.parse(content);
    },
    fileExists,
};
export async function runTriageComments(context, options, deps = defaultTriageDependencies) {
    const { logger } = context;
    const { inputDir, outputDir, month } = options;
    const inputPath = join(inputDir, `${month}.json`);
    if (!(await deps.fileExists(inputPath))) {
        throw new CliError(`Collection file not found: ${inputPath}`);
    }
    const chunk = await deps.readJsonFile(inputPath);
    if (chunk.comments.length === 0) {
        if (context.json) {
            logger.json({ status: 'ok', month, total: 0, comments: [] });
        }
        else {
            logger.warn(`No comments in ${month} to triage.`);
        }
        return;
    }
    // Non-interactive path: emit collection state without prompting.
    // This is the code path reached when --json is set or when running
    // outside a TTY. Interactive triage is reserved for TTY sessions only.
    if (!context.interactive) {
        if (context.json) {
            logger.json({
                status: 'ok',
                month,
                total: chunk.comments.length,
                comments: chunk.comments,
            });
        }
        else {
            logger.info(`Collection ${month}: ${chunk.comments.length} comment(s) pending triage.`);
            logger.info('Re-run in an interactive terminal to triage, or pass --json to retrieve the collection state.');
        }
        return;
    }
    // Interactive path: prompt for each comment (TTY sessions only).
    logger.info(`Triaging ${chunk.comments.length} comments from ${month}...`);
    logger.info('For each comment, enter [k]eep or [d]iscard (default: keep).\n');
    const kept = [];
    const rl = createInterface({ input: process.stdin, output: process.stderr });
    try {
        for (const comment of chunk.comments) {
            printCommentSummary(comment);
            const answer = await askQuestion(rl, `  ${comment.rcId} [k/d]? `);
            const choice = answer.trim().toLowerCase();
            if (choice === 'd' || choice === 'discard') {
                logger.info(`  → Discarded ${comment.rcId}`);
            }
            else {
                kept.push(comment);
                logger.info(`  → Kept ${comment.rcId}`);
            }
            logger.info('');
        }
    }
    finally {
        rl.close();
    }
    await ensureDir(outputDir);
    const outputChunk = { month, comments: kept };
    const outputPath = join(outputDir, `${month}.triaged.json`);
    await writeFile(outputPath, `${JSON.stringify(outputChunk, null, 2)}\n`, 'utf8');
    logger.success(`Triage complete: kept ${kept.length}/${chunk.comments.length} comments → ${outputPath}`);
}
function printCommentSummary(comment) {
    const lines = [
        `  ──── ${comment.rcId} ────`,
        `  PR #${comment.prNumber}: ${comment.prTitle}`,
        `  File: ${comment.filePath}${comment.line ? `:${comment.line}` : ''}`,
        `  Author: ${comment.author} (${comment.createdAt.slice(0, 10)})`,
        `  ${comment.body.length > 200 ? `${comment.body.slice(0, 200)}...` : comment.body}`,
    ];
    for (const line of lines) {
        process.stderr.write(`${line}\n`);
    }
}
function askQuestion(rl, prompt) {
    return new Promise((resolve) => {
        rl.question(prompt, resolve);
    });
}
