use super::IdTemplate;
use crate::{
Compiled, Error, Model, Result,
grammar::{SokfSchema, States},
markdown::is_slug,
};
pub fn schema_for<'a>(
model: &Model,
compiled: &'a Compiled,
type_name: &str,
chosen: Option<usize>,
) -> Result<(Option<usize>, &'a SokfSchema)> {
if type_name == "Schema" {
return Ok((None, &compiled.schema_document));
}
let refuse = |msg: String| Error::New(msg);
let roots: Vec<usize> = model
.knowledges
.iter()
.enumerate()
.filter(|(i, k)| chosen.is_none_or(|c| c == *i) && !k.schemas_for(type_name).is_empty())
.map(|(i, _)| i)
.collect();
let knowledge = match (roots.as_slice(), chosen) {
([], Some(c)) => {
return Err(refuse(format!(
"`{type_name}` has no schema in {}",
model.knowledges[c].root
)));
}
([], None) => return Err(refuse(format!("`{type_name}` has no schema"))),
([one], _) => *one,
_ => return Err(refuse(ambiguous(model, type_name, &roots))),
};
if model.knowledges[knowledge].schemas_for(type_name).len() > 1 {
return Err(refuse(format!(
"more than one schema declares `{type_name}`"
)));
}
let Some((_, schema)) = compiled.for_type(model, knowledge, type_name) else {
return Err(refuse(format!(
"the schema of `{type_name}` does not pass the grammar"
)));
};
Ok((Some(knowledge), schema))
}
fn ambiguous(model: &Model, type_name: &str, roots: &[usize]) -> String {
let names: Vec<String> = roots
.iter()
.map(|&i| model.knowledges[i].root.to_string())
.collect();
let forms: Vec<String> = roots
.iter()
.filter_map(|&i| model.store_name(i))
.map(|store| format!("`{store}:{type_name}`"))
.collect();
let advice = if forms.len() == roots.len() {
format!(". Write {}", forms.join(" or "))
} else {
String::new()
};
format!(
"more than one root declares `{type_name}`: {}{advice}",
names.join(", ")
)
}
pub fn next_seq(
model: &Model,
knowledge: usize,
type_name: &str,
template: &IdTemplate,
) -> Result<u64> {
let refuse = |msg: String| Error::New(msg);
let Some(width) = template.seq_width() else {
return Err(refuse(format!(
"the id template of `{type_name}` has no `seq` placeholder"
)));
};
if let Some(path) = model.broken_in(knowledge).first() {
return Err(refuse(format!(
"{path} has frontmatter that does not parse"
)));
}
let mut highest = 0u64;
for (path, id) in model.ids_of_type(knowledge, type_name) {
match template.seq_of(&id) {
Some(n) => highest = highest.max(n),
None => {
return Err(refuse(format!(
"{path} has an id that does not match the id template"
)));
}
}
}
let next = highest + 1;
if next.to_string().len() > width {
return Err(refuse(format!(
"the next number {next} needs more than {width} digits"
)));
}
Ok(next)
}
pub fn render_id(
template: &IdTemplate,
seq: u64,
slug: Option<&str>,
states: &States,
) -> Result<String> {
let refuse = |msg: String| Error::New(msg);
match slug {
Some(s) if !template.has_slug() => {
return Err(refuse(format!(
"you gave `--slug {s}`, but the id template has no `slug` placeholder"
)));
}
Some(s) if !is_slug(s) => {
return Err(refuse(format!(
"`{s}` is not a valid slug: use lowercase letters and digits in words joined by hyphens"
)));
}
None if template.has_slug() => {
return Err(refuse(
"the id template has a `slug` placeholder, so `--slug` is required".to_string(),
));
}
_ => {}
}
template.render_with(seq, slug, states).map_err(refuse)
}