/**
 * Shared terminal markdown rendering for CLI commands.
 */
import { Marked } from 'marked';
import { markedTerminal } from 'marked-terminal';
let cachedRenderer = null;
function getTerminalWidth() {
    const cols = process.stdout.columns || 80;
    return Math.max(60, Math.min(cols - 2, 100));
}
function getRenderer(width) {
    const resolvedWidth = width ?? getTerminalWidth();
    if (cachedRenderer && cachedRenderer.width === resolvedWidth) {
        return cachedRenderer.marked;
    }
    const marked = new Marked();
    marked.use(markedTerminal({
        showSectionPrefix: false,
        tab: 2,
        width: resolvedWidth,
        reflowText: true,
    }));
    cachedRenderer = { width: resolvedWidth, marked };
    return marked;
}
/**
 * Clean marked-terminal output for release-grade CLI presentation.
 */
export function cleanTerminalMarkdownOutput(raw) {
    let out = raw;
    out = out.replace(/^  \* /gm, '- ');
    out = out.replace(/^    \* /gm, '  - ');
    const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
    out = out.split('\n').filter((line) => {
        if (line === '')
            return true;
        return stripAnsi(line).trim().length > 0;
    }).join('\n');
    out = out.replace(/\n{3,}/g, '\n\n');
    return out;
}
export function looksLikeMarkdownReport(text) {
    const trimmed = String(text || '').trim();
    if (!trimmed)
        return false;
    return /^#{1,3}\s+\S/m.test(trimmed)
        || /^\|.+\|/m.test(trimmed)
        || /^[-*]\s+\*\*/m.test(trimmed);
}
export function renderMarkdownToTerminal(markdown, width) {
    const input = String(markdown || '').trim();
    if (!input)
        return '';
    if (!looksLikeMarkdownReport(input)) {
        return input;
    }
    const rendered = getRenderer(width).parse(input);
    return cleanTerminalMarkdownOutput(rendered);
}
export function summarizeMarkdownReport(markdown) {
    const text = String(markdown || '').trim();
    if (!text || !looksLikeMarkdownReport(text)) {
        return null;
    }
    const lines = text.split('\n');
    let title = '';
    const sections = [];
    for (const line of lines) {
        const h1 = line.match(/^#\s+(.+)$/);
        if (h1 && !title) {
            title = h1[1].replace(/[*_`]/g, '').trim();
            continue;
        }
        const h2 = line.match(/^##\s+(.+)$/);
        if (h2) {
            const section = h2[1].replace(/[*_`]/g, '').trim();
            if (section && sections.length < 8) {
                sections.push(section);
            }
        }
    }
    if (!title) {
        const firstLine = lines.find((line) => line.trim().length > 0)?.trim() || 'Analysis report';
        title = firstLine.replace(/^#+\s*/, '').replace(/[*_`]/g, '').slice(0, 120);
    }
    return {
        title,
        sections,
        charCount: text.length,
    };
}
