/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// @ts-expect-error pdf-parse has no type declarations
import pdfParse from 'pdf-parse';
import mammoth from 'mammoth';
/**
 * Extracts text from a PDF buffer and returns it as markdown.
 * Preserves paragraph breaks. Returns empty string on failure.
 */
export async function extractPdfToMarkdown(data) {
    try {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
        const result = await pdfParse(data);
        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
        const text = result.text ?? '';
        if (!text.trim())
            return '';
        // Split into paragraphs by double-newline or page breaks, normalize whitespace
        const lines = text.split(/\n{2,}/);
        const paragraphs = lines
            .map((line) => line.replace(/\n/g, ' ').replace(/\s+/g, ' ').trim())
            .filter((line) => line.length > 0);
        return paragraphs.join('\n\n');
    }
    catch {
        return '';
    }
}
/**
 * Converts HTML table to a markdown table (best-effort).
 */
function htmlTableToMarkdown(tableHtml) {
    const rows = [];
    const rowRegex = /<tr[^>]*>([\s\S]*?)<\/tr>/gi;
    let rowMatch = rowRegex.exec(tableHtml);
    while (rowMatch) {
        const cellRegex = /<(?:td|th)[^>]*>([\s\S]*?)<\/(?:td|th)>/gi;
        const cells = [];
        let cellMatch = cellRegex.exec(rowMatch[1]);
        while (cellMatch) {
            cells.push(stripHtmlTags(cellMatch[1]).trim());
            cellMatch = cellRegex.exec(rowMatch[1]);
        }
        if (cells.length > 0) {
            rows.push(cells);
        }
        rowMatch = rowRegex.exec(tableHtml);
    }
    if (rows.length === 0)
        return '';
    // Normalize column count
    const maxCols = Math.max(...rows.map((r) => r.length));
    const normalized = rows.map((r) => {
        while (r.length < maxCols)
            r.push('');
        return r;
    });
    const header = `| ${normalized[0].join(' | ')} |`;
    const separator = `| ${normalized[0].map(() => '---').join(' | ')} |`;
    const body = normalized
        .slice(1)
        .map((row) => `| ${row.join(' | ')} |`)
        .join('\n');
    return [header, separator, body].filter(Boolean).join('\n');
}
/**
 * Strips HTML tags from a string, returning plain text.
 */
function stripHtmlTags(html) {
    return html.replace(/<[^>]+>/g, '');
}
/**
 * Converts mammoth HTML output to clean markdown.
 * Maps h1 → #, h2 → ##, h3 → ###, p → paragraph, table → markdown table.
 */
function htmlToMarkdown(html) {
    if (!html?.trim())
        return '';
    let md = html;
    // Convert tables first (before stripping tags)
    md = md.replace(/<table[^>]*>([\s\S]*?)<\/table>/gi, (_match, inner) => '\n\n' + htmlTableToMarkdown(inner) + '\n\n');
    // Convert headings
    md = md.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, (_m, content) => `\n\n# ${stripHtmlTags(content).trim()}\n\n`);
    md = md.replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, (_m, content) => `\n\n## ${stripHtmlTags(content).trim()}\n\n`);
    md = md.replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, (_m, content) => `\n\n### ${stripHtmlTags(content).trim()}\n\n`);
    md = md.replace(/<h4[^>]*>([\s\S]*?)<\/h4>/gi, (_m, content) => `\n\n#### ${stripHtmlTags(content).trim()}\n\n`);
    md = md.replace(/<h5[^>]*>([\s\S]*?)<\/h5>/gi, (_m, content) => `\n\n##### ${stripHtmlTags(content).trim()}\n\n`);
    md = md.replace(/<h6[^>]*>([\s\S]*?)<\/h6>/gi, (_m, content) => `\n\n###### ${stripHtmlTags(content).trim()}\n\n`);
    // Convert list items
    md = md.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_m, content) => `\n- ${stripHtmlTags(content).trim()}`);
    md = md.replace(/<\/?[ou]l[^>]*>/gi, '\n');
    // Convert paragraphs
    md = md.replace(/<p[^>]*>([\s\S]*?)<\/p>/gi, (_m, content) => `\n\n${stripHtmlTags(content).trim()}\n\n`);
    // Convert line breaks
    md = md.replace(/<br\s*\/?>/gi, '\n');
    // Bold and italic
    md = md.replace(/<(?:strong|b)[^>]*>([\s\S]*?)<\/(?:strong|b)>/gi, '**$1**');
    md = md.replace(/<(?:em|i)[^>]*>([\s\S]*?)<\/(?:em|i)>/gi, '*$1*');
    // Strip remaining HTML tags
    md = stripHtmlTags(md);
    // Normalize whitespace: collapse 3+ newlines to 2
    md = md.replace(/\n{3,}/g, '\n\n');
    return md.trim();
}
/**
 * Extracts text from a DOCX buffer and returns it as markdown.
 * Uses mammoth to convert to HTML, then converts HTML to markdown.
 * Returns empty string on failure.
 */
export async function extractDocxToMarkdown(data) {
    try {
        const result = await mammoth.convertToHtml({ buffer: data });
        const html = result.value ?? '';
        if (!html.trim())
            return '';
        return htmlToMarkdown(html);
    }
    catch {
        return '';
    }
}
//# sourceMappingURL=transcript-extractor.js.map