// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
// SPDX-License-Identifier: BSD-2-Clause
//! Generate the test shell program.

use anyhow::{Context as _, Result};
use handlebars::{Context, Handlebars, Helper, HelperResult, Output, RenderContext, RenderError};
use tracing::debug;

use crate::defs::TestData;

const TEMPLATE_NAME: &str = "run-tests";
const TEMPLATE_PATH: &str = "tests/test-data/run-test.sh.hbs";

fn helper_datafile(
    helper: &Helper<'_, '_>,
    _: &Handlebars<'_>,
    _: &Context,
    _: &mut RenderContext<'_, '_>,
    out: &mut (dyn Output),
) -> HelperResult {
    let value = helper
        .param(0)
        .ok_or_else(|| {
            RenderError::new(format!(
                "Internal error: datafile: no parameter in {helper:?}"
            ))
        })?
        .value()
        .as_str()
        .ok_or_else(|| {
            RenderError::new(format!(
                "Internal error: datafile: not a string parameter in {helper:?}"
            ))
        })?;
    let res = if value == "-" {
        "-".to_owned()
    } else if value.starts_with('/') {
        shell_words::quote(value).to_string()
    } else {
        format!("\"$datadir/{value}\"")
    };
    out.write(&res)?;
    Ok(())
}

fn helper_shell_quote(
    helper: &Helper<'_, '_>,
    _: &Handlebars<'_>,
    _: &Context,
    _: &mut RenderContext<'_, '_>,
    out: &mut (dyn Output),
) -> HelperResult {
    let value = helper
        .param(0)
        .ok_or_else(|| {
            RenderError::new(format!(
                "Internal error: shell_quote: no parameter in {helper:?}"
            ))
        })?
        .value()
        .as_str()
        .ok_or_else(|| {
            RenderError::new(format!(
                "Internal error: shell_quote: not a string parameter in {helper:?}"
            ))
        })?;
    let res = shell_words::quote(value);
    out.write(&res)?;
    Ok(())
}

fn helper_shell_join(
    helper: &Helper<'_, '_>,
    _: &Handlebars<'_>,
    _: &Context,
    _: &mut RenderContext<'_, '_>,
    out: &mut (dyn Output),
) -> HelperResult {
    let arr = helper
        .param(0)
        .ok_or_else(|| {
            RenderError::new(format!(
                "Internal error: shell_join: no parameter in {helper:?}"
            ))
        })?
        .value()
        .as_array()
        .ok_or_else(|| {
            RenderError::new(format!(
                "Internal error: shell_join: not an array parameter in {helper:?}"
            ))
        })?
        .iter()
        .map(|item| {
            item.as_str().ok_or_else(|| {
                RenderError::new(format!(
                    "Internal error: shell_join: not a string: {item:?}"
                ))
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    let res = shell_words::join(arr);
    out.write(&res)?;
    Ok(())
}

/// Build a handlebars renderer, load the template, etc.
pub fn generate(test_data: &TestData) -> Result<String> {
    let mut renderer = Handlebars::new();
    renderer.set_strict_mode(true);
    renderer.register_escape_fn(ToOwned::to_owned);
    renderer.register_helper("datafile", Box::new(helper_datafile));
    renderer.register_helper("shell_quote", Box::new(helper_shell_quote));
    renderer.register_helper("shell_join", Box::new(helper_shell_join));
    renderer
        .register_template_file(TEMPLATE_NAME, TEMPLATE_PATH)
        .with_context(|| format!("Could not parse the {TEMPLATE_PATH} template"))?;

    debug!("Rendering {count} tests", count = test_data.tests().len());
    renderer
        .render(TEMPLATE_NAME, test_data)
        .with_context(|| format!("Could not render the {TEMPLATE_NAME} template"))
}
