import { resolveWikilinks } from './wikilinks.js';
import { generateTitlePageHtml, generateCopyrightPageHtml } from './frontmatter.js';
export function compileManuscriptToBookHtml(manuscript, options) {
    // 1. Resolve Wikilinks
    let processed = resolveWikilinks(manuscript);
    // 2. Preprocess manual page breaks `///`
    // Replace lines containing only `///` (with optional whitespace)
    const pageBreakMarker = '<!--BOOK_PAGE_BREAK-->';
    processed = processed.replace(/^[ \t]*\/\/\/[ \t]*$/gm, pageBreakMarker);
    // 3. Simple Markdown to HTML Parser
    let htmlBody = renderMarkdownToHtml(processed, options.resolveImagePath);
    // Replace page break placeholder with actual CSS page break element
    htmlBody = htmlBody.replace(new RegExp(pageBreakMarker, 'g'), '<div class="book-page-break"></div>');
    // 4. Generate Frontmatter HTML
    const titlePageHtml = generateTitlePageHtml(options.metadata);
    const copyrightPageHtml = generateCopyrightPageHtml(options.metadata);
    return `
    <div class="book-interior">
      ${titlePageHtml}
      ${copyrightPageHtml}
      <div class="book-main-content">
        ${htmlBody}
      </div>
    </div>
  `;
}
/**
 * Lightweight, robust Markdown to HTML renderer optimized for paged book typesetting.
 */
function renderMarkdownToHtml(markdown, resolveImagePath) {
    const lines = markdown.split(/\r?\n/);
    const result = [];
    let inCodeBlock = false;
    let codeBlockLang = '';
    let codeBlockBuffer = [];
    let inList = false;
    let listType = 'ul';
    const closeListIfOpen = () => {
        if (inList) {
            result.push(listType === 'ul' ? '</ul>' : '</ol>');
            inList = false;
        }
    };
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        // Fenced Code Blocks ```
        if (line.trim().startsWith('```')) {
            if (inCodeBlock) {
                result.push(`<pre><code class="language-${codeBlockLang}">${escapeHtml(codeBlockBuffer.join('\n'))}</code></pre>`);
                inCodeBlock = false;
                codeBlockBuffer = [];
            }
            else {
                closeListIfOpen();
                inCodeBlock = true;
                codeBlockLang = line.trim().substring(3).trim();
            }
            continue;
        }
        if (inCodeBlock) {
            codeBlockBuffer.push(line);
            continue;
        }
        // Page Break Placeholder
        if (line.includes('<!--BOOK_PAGE_BREAK-->')) {
            closeListIfOpen();
            result.push(line);
            continue;
        }
        // Empty Lines
        if (!line.trim()) {
            closeListIfOpen();
            continue;
        }
        // Headings
        if (line.startsWith('# ')) {
            closeListIfOpen();
            result.push(`<h1 class="book-h1">${formatInline(line.substring(2), resolveImagePath)}</h1>`);
            continue;
        }
        if (line.startsWith('## ')) {
            closeListIfOpen();
            result.push(`<h2 class="book-h2">${formatInline(line.substring(3), resolveImagePath)}</h2>`);
            continue;
        }
        if (line.startsWith('### ')) {
            closeListIfOpen();
            result.push(`<h3 class="book-h3">${formatInline(line.substring(4), resolveImagePath)}</h3>`);
            continue;
        }
        if (line.startsWith('#### ')) {
            closeListIfOpen();
            result.push(`<h4 class="book-h4">${formatInline(line.substring(5), resolveImagePath)}</h4>`);
            continue;
        }
        // Blockquotes
        if (line.startsWith('> ')) {
            closeListIfOpen();
            result.push(`<blockquote><p>${formatInline(line.substring(2), resolveImagePath)}</p></blockquote>`);
            continue;
        }
        // Unordered Lists (* or -)
        if (/^[ \t]*[*`-][ \t]+/.test(line)) {
            if (!inList || listType !== 'ul') {
                closeListIfOpen();
                inList = true;
                listType = 'ul';
                result.push('<ul>');
            }
            const content = line.replace(/^[ \t]*[*`-][ \t]+/, '');
            result.push(`<li>${formatInline(content, resolveImagePath)}</li>`);
            continue;
        }
        // Ordered Lists (1. 2.)
        if (/^[ \t]*\d+\.[ \t]+/.test(line)) {
            if (!inList || listType !== 'ol') {
                closeListIfOpen();
                inList = true;
                listType = 'ol';
                result.push('<ol>');
            }
            const content = line.replace(/^[ \t]*\d+\.[ \t]+/, '');
            result.push(`<li>${formatInline(content, resolveImagePath)}</li>`);
            continue;
        }
        // Horizontal Rule
        if (/^[ \t]*---[ \t]*$/.test(line) || /^[ \t]*\*\*\*[ \t]*$/.test(line)) {
            closeListIfOpen();
            result.push('<hr class="book-hr" />');
            continue;
        }
        // Paragraph
        closeListIfOpen();
        result.push(`<p>${formatInline(line, resolveImagePath)}</p>`);
    }
    closeListIfOpen();
    return result.join('\n');
}
function formatInline(text, resolveImagePath) {
    let res = escapeHtml(text);
    // Markdown Images ![alt](src)
    res = res.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_match, alt, src) => {
        const finalSrc = resolveImagePath ? resolveImagePath(src) : src;
        return `<img class="book-image" src="${finalSrc}" alt="${alt}" />`;
    });
    // Links [text](url)
    res = res.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
    // Bold & Italic ***text***
    res = res.replace(/\*\*\*([^*]+)\*\*\*/g, '<strong><em>$1</em></strong>');
    // Bold **text**
    res = res.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
    // Italic *text*
    res = res.replace(/\*([^*]+)\*/g, '<em>$1</em>');
    // Code `code`
    res = res.replace(/`([^`]+)`/g, '<code>$1</code>');
    return res;
}
function escapeHtml(text) {
    return text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}
//# sourceMappingURL=compiler.js.map