use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::Error;
const DEFAULT_MODEL: &str = "jev-latest";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Request {
pub state: Value,
pub model: String,
pub questions: BTreeMap<String, Question>,
}
impl Request {
pub fn new(state: impl Into<Value>) -> Self {
Self {
state: state.into(),
model: DEFAULT_MODEL.to_owned(),
questions: BTreeMap::new(),
}
}
#[must_use]
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = model.into();
self
}
#[must_use]
pub fn with_question(mut self, id: impl Into<String>, question: Question) -> Self {
self.questions.insert(id.into(), question);
self
}
pub fn insert_question(
&mut self,
id: impl Into<String>,
question: Question,
) -> Option<Question> {
self.questions.insert(id.into(), question)
}
pub fn validate(&self) -> Result<(), Error> {
if !is_state(&self.state) {
return Err(Error::Validation {
field: "state".to_owned(),
message: "must be a string, object, or array".to_owned(),
});
}
for (id, question) in &self.questions {
question.validate(id)?;
}
Ok(())
}
}
impl Default for Request {
fn default() -> Self {
Self::new(Value::String(String::new()))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NoulCriteria {
#[serde(default, rename = "true")]
pub when_true: Value,
#[serde(default, rename = "false")]
pub when_false: Value,
}
impl NoulCriteria {
pub fn new(when_true: impl Into<Value>, when_false: impl Into<Value>) -> Self {
Self {
when_true: when_true.into(),
when_false: when_false.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Question {
Noul {
instructions: Value,
#[serde(skip_serializing_if = "Option::is_none")]
criteria: Option<NoulCriteria>,
},
Choice {
instructions: Value,
criteria: BTreeMap<String, Value>,
},
Score {
instructions: Value,
criteria: Vec<Value>,
},
}
impl Question {
pub fn noul(instructions: impl Into<Value>) -> Self {
Self::Noul {
instructions: instructions.into(),
criteria: None,
}
}
pub fn noul_with_criteria(instructions: impl Into<Value>, criteria: NoulCriteria) -> Self {
Self::Noul {
instructions: instructions.into(),
criteria: Some(criteria),
}
}
pub fn choice(instructions: impl Into<Value>, criteria: BTreeMap<String, Value>) -> Self {
Self::Choice {
instructions: instructions.into(),
criteria,
}
}
pub fn score(instructions: impl Into<Value>, criteria: Vec<Value>) -> Self {
Self::Score {
instructions: instructions.into(),
criteria,
}
}
fn validate(&self, id: &str) -> Result<(), Error> {
let instructions = match self {
Self::Noul { instructions, .. }
| Self::Choice { instructions, .. }
| Self::Score { instructions, .. } => instructions,
};
validate_entry(instructions, format!("questions.{id}.instructions"))?;
match self {
Self::Noul {
criteria: Some(criteria),
..
} => {
validate_entry(&criteria.when_true, format!("questions.{id}.criteria.true"))?;
validate_entry(
&criteria.when_false,
format!("questions.{id}.criteria.false"),
)
}
Self::Noul { criteria: None, .. } => Ok(()),
Self::Choice { criteria, .. } => {
if criteria.is_empty() {
return Err(Error::Validation {
field: format!("questions.{id}.criteria"),
message: "must contain at least one option".to_owned(),
});
}
for (option, description) in criteria {
validate_entry(description, format!("questions.{id}.criteria.{option}"))?;
}
Ok(())
}
Self::Score { criteria, .. } => {
if criteria.len() < 2 {
return Err(Error::Validation {
field: format!("questions.{id}.criteria"),
message: "must contain at least two levels".to_owned(),
});
}
for (level, description) in criteria.iter().enumerate() {
validate_entry(description, format!("questions.{id}.criteria[{level}]"))?;
}
Ok(())
}
}
}
}
fn is_state(value: &Value) -> bool {
matches!(value, Value::String(_) | Value::Object(_) | Value::Array(_))
}
fn validate_entry(value: &Value, field: String) -> Result<(), Error> {
if matches!(
value,
Value::String(_) | Value::Object(_) | Value::Array(_) | Value::Null
) {
Ok(())
} else {
Err(Error::Validation {
field,
message: "must be a string, object, array, or null".to_owned(),
})
}
}