//! Per-form rendering of a single master example.
//!
//! - JSON form: read the on-disk canonical bytes verbatim, emit a
//!   ```json``` fenced block.
//! - AIL form: load the example via ailang_core::load_module, print
//!   via ailang_surface::print, emit a ```ail``` fenced block.

use anyhow::{anyhow, Context, Result};
use std::path::Path;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Form {
    Json,
    Ail,
}

pub fn render_example(examples_dir: &Path, id: &str, form: Form) -> Result<String> {
    let path = examples_dir.join(format!("{id}.ail.json"));
    if !path.exists() {
        return Err(anyhow!(
            "example id `{id}` references missing fixture at {}",
            path.display()
        ));
    }
    match form {
        Form::Json => {
            let bytes = std::fs::read_to_string(&path)
                .with_context(|| format!("reading {}", path.display()))?;
            Ok(format!("```json\n{}\n```\n", bytes.trim_end()))
        }
        Form::Ail => {
            let module = ailang_core::load_module(&path)
                .with_context(|| format!("load_module on {}", path.display()))?;
            let text = ailang_surface::print(&module);
            Ok(format!("```ail\n{}\n```\n", text.trim_end()))
        }
    }
}
