isis-report-lib 0.1.0

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
Documentation
//! Public API (sync + async aliases).
//!
//! The canonical names are idiomatic Rust (`generate_pdf`,
//! `generate_pdf_async`, `render_html`, ...). Python-compatible aliases
//! (`agenerate_pdf`, `arender_html`, ...) are provided for migration.

use std::path::Path;

use crate::error::{Error, Result};
use crate::export::{build_workbook, collect_tables, render_csv};
use crate::service::prepare_report;
use crate::text::{sanitize_text, wrap_report_text};
use crate::toon::parse_toon;
use crate::value::Value;
use crate::Limits;
use crate::ReportService;

/// Render only the intermediate HTML (sync, no browser).
pub fn render_html(
    payload: &Value,
    template_dir: Option<&Path>,
    template_name: &str,
    inline_css: bool,
    limits: Option<Limits>,
) -> Result<String> {
    let service = ReportService {
        template_dir: template_dir.map(Path::to_path_buf),
        template_name: template_name.to_string(),
        inline_css,
        limits,
        ..ReportService::default()
    };
    service.render_html(payload)
}

/// Render HTML from `.toon` text.
pub fn render_html_from_toon(
    text: &str,
    template_dir: Option<&Path>,
    template_name: &str,
    inline_css: bool,
    limits: Option<Limits>,
) -> Result<String> {
    render_html(&parse_toon(text)?, template_dir, template_name, inline_css, limits)
}

/// Generate CSV text (no browser).
pub fn generate_csv(payload: &Value, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
    let prepared = prepare_report(payload, limits)?;
    let meta = prepared.meta.to_value();
    let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
    let text = render_csv(&tables, &summaries, Some(&meta), delimiter)?;
    Ok(if bom { format!("\u{feff}{text}") } else { text })
}

/// Generate CSV from `.toon` text.
pub fn generate_csv_from_toon(text: &str, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
    generate_csv(&parse_toon(text)?, delimiter, bom, limits)
}

/// Render a visible-only, sanitized plain-text export (no browser).
pub fn render_text(payload: &Value, sanitize: bool, limits: Option<Limits>) -> Result<String> {
    let text = generate_csv(payload, ',', false, limits)?;
    let text = if sanitize { sanitize_text(&text) } else { text };
    Ok(wrap_report_text(&text))
}

/// Render plain text from `.toon` text.
pub fn render_text_from_toon(text: &str, sanitize: bool, limits: Option<Limits>) -> Result<String> {
    render_text(&parse_toon(text)?, sanitize, limits)
}

/// Generate an `.xlsx` workbook (sync, no browser).
pub fn generate_xlsx(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
    let prepared = prepare_report(payload, limits)?;
    let meta = prepared.meta.to_value();
    let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
    build_workbook(&tables, &summaries, Some(&meta))
}

/// Generate `.xlsx` from `.toon` text.
pub fn generate_xlsx_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_xlsx(&parse_toon(text)?, limits)
}

/// Generate a PDF (sync). Requires the `pdf` feature and Chromium.
#[cfg(not(feature = "pdf"))]
pub fn generate_pdf(_payload: &Value, _limits: Option<Limits>) -> Result<Vec<u8>> {
    Err(Error::FeatureDisabled("PDF generation requires the 'pdf' feature and Chromium"))
}

/// Generate a PDF (sync). Requires the `pdf` feature and Chromium.
///
/// The page format, orientation and margins come from `meta.page`; other
/// options use their defaults. Use [`generate_pdf_with`] to override them.
#[cfg(feature = "pdf")]
pub fn generate_pdf(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
    let service = ReportService {
        limits,
        ..ReportService::default()
    };
    service.generate_pdf(payload)
}

/// Generate a PDF with explicit options, template directory and template.
#[cfg(feature = "pdf")]
pub fn generate_pdf_with(
    payload: &Value,
    options: &crate::pdf_backend::PdfOptions,
    template_dir: Option<&Path>,
    template_name: &str,
    limits: Option<Limits>,
) -> Result<Vec<u8>> {
    let service = ReportService {
        template_dir: template_dir.map(Path::to_path_buf),
        template_name: template_name.to_string(),
        limits,
        pdf_options: Some(options.clone()),
        ..ReportService::default()
    };
    service.generate_pdf(payload)
}

/// Generate a PDF from `.toon` text.
pub fn generate_pdf_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_pdf(&parse_toon(text)?, limits)
}

/// Generate a PDF from `.toon` text with explicit options.
#[cfg(feature = "pdf")]
pub fn generate_pdf_from_toon_with(
    text: &str,
    options: &crate::pdf_backend::PdfOptions,
    template_dir: Option<&Path>,
    template_name: &str,
    limits: Option<Limits>,
) -> Result<Vec<u8>> {
    generate_pdf_with(&parse_toon(text)?, options, template_dir, template_name, limits)
}

#[cfg(feature = "pdf")]
fn validate_concurrency(max_concurrency: usize) -> Result<()> {
    if max_concurrency < 1 {
        return Err(Error::option(format!("max_concurrency must be >= 1, got {max_concurrency}")));
    }
    Ok(())
}

/// Generate several PDFs concurrently (feature `pdf`).
#[cfg(feature = "pdf")]
pub async fn generate_many_async(
    payloads: &[Value],
    max_concurrency: usize,
    options: Option<&crate::pdf_backend::PdfOptions>,
    template_dir: Option<&Path>,
    template_name: &str,
    limits: Option<Limits>,
) -> Result<Vec<Vec<u8>>> {
    use futures::StreamExt;

    validate_concurrency(max_concurrency)?;
    let service = ReportService {
        template_dir: template_dir.map(Path::to_path_buf),
        template_name: template_name.to_string(),
        limits,
        pdf_options: options.cloned(),
        ..ReportService::default()
    };
    let results: Vec<Result<Vec<u8>>> = futures::stream::iter(payloads.iter().cloned().map(|payload| {
        let service = service.clone();
        async move { service.generate_pdf_async(&payload).await }
    }))
    .buffered(max_concurrency)
    .collect()
    .await;
    results.into_iter().collect()
}

/// Generate several PDFs concurrently (sync, feature `pdf`).
#[cfg(feature = "pdf")]
pub fn generate_many(payloads: &[Value], max_concurrency: usize, limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
    validate_concurrency(max_concurrency)?;
    let payloads = payloads.to_vec();
    let outcome = std::thread::spawn(move || -> Result<Vec<Vec<u8>>> {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|error| Error::pdf(format!("Cannot start the PDF runtime: {error}")))?;
        runtime.block_on(generate_many_async(&payloads, max_concurrency, None, None, "tabular.jinja", limits))
    })
    .join()
    .map_err(|_| Error::pdf("PDF worker thread panicked"))?;
    outcome
}

/// Generate several PDFs concurrently (requires the `pdf` feature).
#[cfg(not(feature = "pdf"))]
pub fn generate_many(_payloads: &[Value], _max_concurrency: usize, _limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
    Err(Error::FeatureDisabled("PDF generation requires the 'pdf' feature and Chromium"))
}

/// Generate several PDFs concurrently with explicit options.
#[cfg(feature = "pdf")]
pub fn generate_many_with(
    payloads: &[Value],
    options: &crate::pdf_backend::PdfOptions,
    max_concurrency: usize,
    template_dir: Option<&Path>,
    template_name: &str,
    limits: Option<Limits>,
) -> Result<Vec<Vec<u8>>> {
    validate_concurrency(max_concurrency)?;
    let payloads = payloads.to_vec();
    let options = options.clone();
    let template_dir = template_dir.map(Path::to_path_buf);
    let template_name = template_name.to_string();
    std::thread::spawn(move || -> Result<Vec<Vec<u8>>> {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|error| Error::pdf(format!("Cannot start the PDF runtime: {error}")))?;
        runtime.block_on(generate_many_async(
            &payloads,
            max_concurrency,
            Some(&options),
            template_dir.as_deref(),
            &template_name,
            limits,
        ))
    })
    .join()
    .map_err(|_| Error::pdf("PDF worker thread panicked"))?
}

/// Async HTML render (parity alias).
pub async fn render_html_async(
    payload: &Value,
    template_dir: Option<&Path>,
    template_name: &str,
    inline_css: bool,
    limits: Option<Limits>,
) -> Result<String> {
    render_html(payload, template_dir, template_name, inline_css, limits)
}

/// Async CSV export (parity alias).
pub async fn generate_csv_async(payload: &Value, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
    generate_csv(payload, delimiter, bom, limits)
}

/// Async text export (parity alias).
pub async fn render_text_async(payload: &Value, sanitize: bool, limits: Option<Limits>) -> Result<String> {
    render_text(payload, sanitize, limits)
}

/// Async XLSX export (parity alias).
pub async fn generate_xlsx_async(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_xlsx(payload, limits)
}

/// Async PDF export (parity alias).
#[cfg(not(feature = "pdf"))]
pub async fn generate_pdf_async(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_pdf(payload, limits)
}

/// Async PDF export (parity alias).
#[cfg(feature = "pdf")]
pub async fn generate_pdf_async(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
    let service = ReportService {
        limits,
        ..ReportService::default()
    };
    service.generate_pdf_async(payload).await
}

/// Async PDF export with explicit options and template selection.
#[cfg(feature = "pdf")]
pub async fn generate_pdf_with_async(
    payload: &Value,
    options: &crate::pdf_backend::PdfOptions,
    template_dir: Option<&Path>,
    template_name: &str,
    limits: Option<Limits>,
) -> Result<Vec<u8>> {
    let service = ReportService {
        template_dir: template_dir.map(Path::to_path_buf),
        template_name: template_name.to_string(),
        limits,
        pdf_options: Some(options.clone()),
        ..ReportService::default()
    };
    service.generate_pdf_async(payload).await
}

/// Python-compatible alias.
pub fn agenerate_pdf(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_pdf(payload, limits)
}

/// Python-compatible alias.
pub fn agenerate_csv(payload: &Value, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
    generate_csv(payload, delimiter, bom, limits)
}

/// Python-compatible alias.
pub fn agenerate_xlsx(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_xlsx(payload, limits)
}

/// Python-compatible alias.
pub fn arender_html(
    payload: &Value,
    template_dir: Option<&Path>,
    template_name: &str,
    inline_css: bool,
    limits: Option<Limits>,
) -> Result<String> {
    render_html(payload, template_dir, template_name, inline_css, limits)
}

/// Python-compatible alias.
pub fn arender_text(payload: &Value, sanitize: bool, limits: Option<Limits>) -> Result<String> {
    render_text(payload, sanitize, limits)
}

/// Python-compatible alias.
pub async fn agenerate_pdf_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_pdf_async(&parse_toon(text)?, limits).await
}

/// Python-compatible alias.
pub async fn agenerate_csv_from_toon(text: &str, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
    generate_csv_from_toon(text, delimiter, bom, limits)
}

/// Python-compatible alias.
pub async fn agenerate_xlsx_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
    generate_xlsx_from_toon(text, limits)
}

/// Python-compatible alias.
pub async fn arender_html_from_toon(
    text: &str,
    template_dir: Option<&Path>,
    template_name: &str,
    inline_css: bool,
    limits: Option<Limits>,
) -> Result<String> {
    render_html_from_toon(text, template_dir, template_name, inline_css, limits)
}

/// Python-compatible alias.
pub async fn arender_text_from_toon(text: &str, sanitize: bool, limits: Option<Limits>) -> Result<String> {
    render_text_from_toon(text, sanitize, limits)
}

/// Python-compatible alias; runs the batch on the async PDF pipeline.
#[cfg(feature = "pdf")]
pub async fn agenerate_many(payloads: &[Value], max_concurrency: usize, limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
    generate_many_async(payloads, max_concurrency, None, None, "tabular.jinja", limits).await
}

/// Python-compatible alias (requires the `pdf` feature).
#[cfg(not(feature = "pdf"))]
pub async fn agenerate_many(_payloads: &[Value], _max_concurrency: usize, _limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
    Err(Error::FeatureDisabled("PDF generation requires the 'pdf' feature and Chromium"))
}