/**
 * src/media/pdf.ts
 * توليد المستندات — PDF and document generation using Chrome headless
 * Reports, invoices (ZATCA-style), and markdown → HTML conversion
 */
import { writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { createChildLogger } from '../utils/logger.js';
const log = createChildLogger('media:pdf');
const execFileAsync = promisify(execFile);
const TMP_DIR = '/tmp/muassis-pdf';
const CHROME_PATH = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
// ─── Helpers ─────────────────────────────────────────────────────────
async function ensureTmpDir() {
    await mkdir(TMP_DIR, { recursive: true });
}
/**
 * Base HTML template with Arabic RTL support and beautiful styling
 */
function wrapInHTMLPage(bodyContent, title, rtl = true) {
    return `<!DOCTYPE html>
<html lang="${rtl ? 'ar' : 'en'}" dir="${rtl ? 'rtl' : 'ltr'}">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${escapeHtml(title)}</title>
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Noto+Sans+Arabic:wght@300;400;500;600;700&display=swap');
    
    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    body {
      font-family: 'Noto Sans Arabic', 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      font-size: 14px;
      line-height: 1.7;
      color: #1a1a2e;
      background: #ffffff;
      direction: ${rtl ? 'rtl' : 'ltr'};
      padding: 40px;
    }
    
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 3px solid #6366f1;
      padding-bottom: 20px;
      margin-bottom: 30px;
    }
    
    .brand {
      font-size: 24px;
      font-weight: 700;
      color: #6366f1;
    }
    
    .brand-sub {
      font-size: 12px;
      color: #64748b;
      font-weight: 400;
    }
    
    h1 { font-size: 22px; font-weight: 700; color: #1e293b; margin-bottom: 16px; }
    h2 { font-size: 18px; font-weight: 600; color: #334155; margin: 24px 0 12px; }
    h3 { font-size: 15px; font-weight: 600; color: #475569; margin: 16px 0 8px; }
    
    p { margin-bottom: 10px; color: #334155; }
    
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 16px 0;
    }
    
    th {
      background: #6366f1;
      color: white;
      padding: 10px 14px;
      text-align: ${rtl ? 'right' : 'left'};
      font-weight: 600;
      font-size: 13px;
    }
    
    td {
      padding: 10px 14px;
      border-bottom: 1px solid #e2e8f0;
      font-size: 13px;
    }
    
    tr:nth-child(even) { background: #f8fafc; }
    tr:hover { background: #f1f5f9; }
    
    .stat-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
      gap: 16px;
      margin: 20px 0;
    }
    
    .stat-card {
      background: linear-gradient(135deg, #f8fafc, #eef2ff);
      border: 1px solid #e0e7ff;
      border-radius: 12px;
      padding: 20px;
      text-align: center;
    }
    
    .stat-value {
      font-size: 28px;
      font-weight: 700;
      color: #6366f1;
    }
    
    .stat-label {
      font-size: 12px;
      color: #64748b;
      margin-top: 4px;
    }
    
    .footer {
      margin-top: 40px;
      padding-top: 16px;
      border-top: 1px solid #e2e8f0;
      text-align: center;
      font-size: 11px;
      color: #94a3b8;
    }
    
    .invoice-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30px;
    }
    
    .invoice-info { font-size: 13px; color: #475569; }
    .invoice-info strong { color: #1e293b; }
    
    .total-row {
      font-weight: 700;
      background: #eef2ff !important;
      font-size: 15px;
    }
    
    .qr-placeholder {
      width: 120px;
      height: 120px;
      border: 2px dashed #cbd5e1;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 11px;
      color: #94a3b8;
      margin-top: 16px;
    }
    
    .zatca-notice {
      background: #fef3c7;
      border: 1px solid #fcd34d;
      border-radius: 8px;
      padding: 12px 16px;
      font-size: 12px;
      color: #92400e;
      margin-top: 20px;
    }
    
    .section { margin-bottom: 24px; }
    
    code {
      background: #f1f5f9;
      padding: 2px 6px;
      border-radius: 4px;
      font-size: 13px;
    }
    
    pre {
      background: #1e293b;
      color: #e2e8f0;
      padding: 16px;
      border-radius: 8px;
      overflow-x: auto;
      margin: 12px 0;
    }
    
    ul, ol { padding-inline-start: 24px; margin: 8px 0; }
    li { margin: 4px 0; }
    
    blockquote {
      border-inline-start: 4px solid #6366f1;
      padding: 8px 16px;
      background: #f8fafc;
      margin: 12px 0;
      color: #475569;
    }
  </style>
</head>
<body>
  ${bodyContent}
</body>
</html>`;
}
function escapeHtml(text) {
    return text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}
function formatNumber(num) {
    return new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    }).format(num);
}
// ─── PDF Generation ──────────────────────────────────────────────────
/**
 * تحويل HTML إلى PDF — Convert HTML to PDF using Chrome headless
 */
export async function generatePDF(htmlContent, outputPath) {
    await ensureTmpDir();
    // Write HTML to a temp file
    const htmlPath = join(TMP_DIR, `temp-${Date.now()}.html`);
    await writeFile(htmlPath, htmlContent, 'utf-8');
    log.debug({ htmlPath, outputPath }, 'Generating PDF with Chrome headless');
    try {
        await execFileAsync(CHROME_PATH, [
            '--headless=new',
            '--disable-gpu',
            '--no-sandbox',
            '--disable-software-rasterizer',
            `--print-to-pdf=${outputPath}`,
            '--print-to-pdf-no-header',
            '--no-pdf-header-footer',
            htmlPath,
        ], {
            timeout: 30_000,
        });
        log.info({ outputPath }, 'PDF generated successfully');
        return outputPath;
    }
    catch (error) {
        log.error({ error, htmlPath, outputPath }, 'Chrome headless PDF generation failed');
        throw new Error(`PDF generation failed: ${error instanceof Error ? error.message : String(error)}`);
    }
}
// ─── Report Generation ───────────────────────────────────────────────
/**
 * تقرير الأعمال — Generate a styled business report PDF
 */
export async function generateReport(tenantId, reportType, data) {
    const reportTypeLabels = {
        daily: { ar: 'تقرير يومي', en: 'Daily Report' },
        weekly: { ar: 'تقرير أسبوعي', en: 'Weekly Report' },
        monthly: { ar: 'تقرير شهري', en: 'Monthly Report' },
    };
    const typeLabel = reportTypeLabels[reportType] || reportTypeLabels.daily;
    const now = new Date();
    const dateStr = now.toLocaleDateString('ar-SA', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
    });
    let bodyHtml = `
    <div class="header">
      <div>
        <div class="brand">TaseesAI تأسيس</div>
        <div class="brand-sub">منصة الذكاء الاصطناعي للأعمال</div>
      </div>
      <div style="text-align: left;">
        <div style="font-size: 13px; color: #64748b;">${dateStr}</div>
        <div style="font-size: 11px; color: #94a3b8;">Tenant: ${escapeHtml(tenantId)}</div>
      </div>
    </div>
    
    <h1>${escapeHtml(data.title || typeLabel.ar)} — ${typeLabel.en}</h1>
    ${data.period ? `<p style="color: #64748b; margin-bottom: 24px;">الفترة: ${escapeHtml(data.period)}</p>` : ''}
  `;
    // Stats grid
    if (data.stats?.length) {
        bodyHtml += '<div class="stat-grid">';
        for (const s of data.stats) {
            bodyHtml += `
        <div class="stat-card">
          <div class="stat-value">${escapeHtml(String(s.value))}</div>
          <div class="stat-label">${escapeHtml(s.label)}</div>
        </div>`;
        }
        bodyHtml += '</div>';
    }
    // Sections
    if (data.sections?.length) {
        for (const section of data.sections) {
            bodyHtml += `
        <div class="section">
          <h2>${escapeHtml(section.title)}</h2>
          <p>${section.content}</p>
        </div>`;
        }
    }
    // Tables
    if (data.tables?.length) {
        for (const table of data.tables) {
            bodyHtml += `<div class="section"><h2>${escapeHtml(table.title)}</h2><table>`;
            bodyHtml += '<thead><tr>';
            for (const h of table.headers) {
                bodyHtml += `<th>${escapeHtml(h)}</th>`;
            }
            bodyHtml += '</tr></thead><tbody>';
            for (const row of table.rows) {
                bodyHtml += '<tr>';
                for (const cell of row) {
                    bodyHtml += `<td>${escapeHtml(cell)}</td>`;
                }
                bodyHtml += '</tr>';
            }
            bodyHtml += '</tbody></table></div>';
        }
    }
    bodyHtml += `
    <div class="footer">
      تم إنشاء هذا التقرير تلقائياً بواسطة المؤسس — TaseesAI<br>
      Generated automatically by Al Moasis — TaseesAI Platform
    </div>`;
    const fullHtml = wrapInHTMLPage(bodyHtml, `${typeLabel.ar} - TaseesAI`);
    const outputPath = join(TMP_DIR, `report-${tenantId}-${reportType}-${Date.now()}.pdf`);
    return generatePDF(fullHtml, outputPath);
}
// ─── Invoice Generation (ZATCA-style) ────────────────────────────────
/**
 * فاتورة ضريبية — Generate ZATCA-compliant invoice PDF
 */
export async function generateInvoice(tenantId, invoiceData) {
    const { customerName, items, vatRate, invoiceNumber, date } = invoiceData;
    // Calculate subtotal, VAT, and grand total
    let subtotal = 0;
    const computedItems = items.map(item => {
        const lineTotal = item.quantity * item.unitPrice;
        subtotal += lineTotal;
        return { ...item, lineTotal };
    });
    const vatAmount = subtotal * (vatRate / 100);
    const grandTotal = subtotal + vatAmount;
    const bodyHtml = `
    <div class="header">
      <div>
        <div class="brand">TaseesAI تأسيس</div>
        <div class="brand-sub">فاتورة ضريبية مبسطة — Simplified Tax Invoice</div>
      </div>
      <div style="text-align: left;">
        <div style="font-weight: 600; color: #1e293b;">فاتورة رقم: ${escapeHtml(invoiceNumber)}</div>
        <div style="font-size: 13px; color: #64748b;">Invoice #${escapeHtml(invoiceNumber)}</div>
      </div>
    </div>
    
    <div class="invoice-header">
      <div class="invoice-info">
        <p><strong>العميل / Customer:</strong> ${escapeHtml(customerName)}</p>
        <p><strong>التاريخ / Date:</strong> ${escapeHtml(date)}</p>
      </div>
      <div class="invoice-info" style="text-align: left;">
        <p><strong>المورد / Seller:</strong> TaseesAI</p>
        <p><strong>الرقم الضريبي / VAT ID:</strong> —</p>
      </div>
    </div>
    
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>الوصف / Description</th>
          <th>الكمية / Qty</th>
          <th>سعر الوحدة / Unit Price</th>
          <th>الإجمالي / Total</th>
        </tr>
      </thead>
      <tbody>
        ${computedItems.map((item, i) => `
          <tr>
            <td>${i + 1}</td>
            <td>${escapeHtml(item.description)}</td>
            <td>${item.quantity}</td>
            <td>${formatNumber(item.unitPrice)} SAR</td>
            <td>${formatNumber(item.lineTotal)} SAR</td>
          </tr>
        `).join('')}
        <tr>
          <td colspan="4" style="text-align: left; font-weight: 600;">المجموع الفرعي / Subtotal</td>
          <td style="font-weight: 600;">${formatNumber(subtotal)} SAR</td>
        </tr>
        <tr>
          <td colspan="4" style="text-align: left;">ضريبة القيمة المضافة / VAT (${vatRate}%)</td>
          <td>${formatNumber(vatAmount)} SAR</td>
        </tr>
        <tr class="total-row">
          <td colspan="4" style="text-align: left;">الإجمالي / Grand Total</td>
          <td>${formatNumber(grandTotal)} SAR</td>
        </tr>
      </tbody>
    </table>
    
    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-top: 30px;">
      <div>
        <h3>رمز ZATCA / ZATCA QR Code</h3>
        <div class="qr-placeholder">
          QR Code<br>ZATCA
        </div>
      </div>
      <div style="max-width: 300px;">
        <div class="zatca-notice">
          ⚠️ هذه فاتورة ضريبية مبسطة طبقاً لمتطلبات هيئة الزكاة والضريبة والجمارك (ZATCA).<br>
          This is a simplified tax invoice per ZATCA requirements.
        </div>
      </div>
    </div>
    
    <div class="footer">
      تم إنشاء هذه الفاتورة تلقائياً بواسطة المؤسس — TaseesAI<br>
      Generated automatically by Al Moasis — TaseesAI Platform
    </div>`;
    const fullHtml = wrapInHTMLPage(bodyHtml, `فاتورة ${invoiceNumber} — TaseesAI`);
    const outputPath = join(TMP_DIR, `invoice-${tenantId}-${invoiceNumber}-${Date.now()}.pdf`);
    return generatePDF(fullHtml, outputPath);
}
// ─── Markdown → HTML ─────────────────────────────────────────────────
/**
 * تحويل ماركداون — Convert markdown to styled HTML with Arabic support
 * Simple parser (no external deps) — handles common markdown patterns
 */
export function markdownToHTML(markdown, rtl = true) {
    let html = escapeHtml(markdown);
    // Headers
    html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
    html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
    html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
    // Bold & italic
    html = html.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
    html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
    html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
    // Inline code
    html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
    // Code blocks
    html = html.replace(/```[\w]*\n([\s\S]*?)```/g, '<pre>$1</pre>');
    // Blockquotes
    html = html.replace(/^&gt; (.+)$/gm, '<blockquote>$1</blockquote>');
    // Unordered lists
    html = html.replace(/^[*-] (.+)$/gm, '<li>$1</li>');
    html = html.replace(/(<li>.*<\/li>\n?)+/g, '<ul>$&</ul>');
    // Ordered lists
    html = html.replace(/^\d+\. (.+)$/gm, '<li>$1</li>');
    // Horizontal rule
    html = html.replace(/^---$/gm, '<hr>');
    // Links
    html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
    // Paragraphs: wrap remaining plain text lines
    html = html.replace(/^(?!<[hupblo]|<li|<hr|<pre|<code|<block)(.+)$/gm, '<p>$1</p>');
    // Clean up empty lines
    html = html.replace(/\n{3,}/g, '\n\n');
    return wrapInHTMLPage(html, 'Document', rtl);
}
//# sourceMappingURL=pdf.js.map