use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub type Description = Option<Value>;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct NoulCriteria {
#[serde(skip_serializing_if = "Option::is_none")]
pub r#true: Description,
#[serde(skip_serializing_if = "Option::is_none")]
pub r#false: Description,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Noul {
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Description,
#[serde(skip_serializing_if = "Option::is_none")]
pub criteria: Option<NoulCriteria>,
}
impl Noul {
pub fn new(instructions: impl Into<Value>) -> Self {
Self {
instructions: Some(instructions.into()),
criteria: None,
}
}
#[must_use = "the returned Noul should be used"]
pub fn with_criteria(mut self, criteria: NoulCriteria) -> Self {
self.criteria = Some(criteria);
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Choice {
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Description,
pub criteria: HashMap<String, Description>,
}
impl Choice {
pub fn new(instructions: impl Into<Value>, criteria: HashMap<String, Description>) -> Self {
Self {
instructions: Some(instructions.into()),
criteria,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Score {
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Description,
pub criteria: Vec<Description>,
}
impl Score {
pub fn new(instructions: impl Into<Value>, criteria: Vec<Description>) -> Self {
Self {
instructions: Some(instructions.into()),
criteria,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum Question {
#[serde(rename = "noul")]
Noul(Noul),
#[serde(rename = "choice")]
Choice(Choice),
#[serde(rename = "score")]
Score(Score),
}
impl From<Noul> for Question {
fn from(q: Noul) -> Self {
Question::Noul(q)
}
}
impl From<Choice> for Question {
fn from(q: Choice) -> Self {
Question::Choice(q)
}
}
impl From<Score> for Question {
fn from(q: Score) -> Self {
Question::Score(q)
}
}
pub fn noul(instructions: impl Into<Value>) -> Noul {
Noul::new(instructions)
}
pub fn choice(instructions: impl Into<Value>, criteria: HashMap<String, Description>) -> Choice {
Choice::new(instructions, criteria)
}
pub fn score(instructions: impl Into<Value>, criteria: Vec<Description>) -> Score {
Score::new(instructions, criteria)
}
pub(crate) fn validate_questions(
questions: &HashMap<String, Question>,
) -> crate::error::Result<()> {
if questions.is_empty() {
return Err(crate::error::TypeSafeError::new(
crate::error::ErrorKind::Validation("At least one question is required.".to_string()),
));
}
for (name, question) in questions {
if name.trim().is_empty() {
return Err(crate::error::TypeSafeError::new(
crate::error::ErrorKind::Validation(
"Question names cannot be empty or whitespace.".to_string(),
),
));
}
match question {
Question::Choice(choice) => {
if choice.criteria.len() < 2 {
return Err(crate::error::TypeSafeError::new(
crate::error::ErrorKind::Validation(format!(
"Choice question \"{name}\" has {} criteria; at least two choices are required.",
choice.criteria.len()
)),
));
}
}
Question::Score(score) => {
if score.criteria.len() < 2 {
return Err(crate::error::TypeSafeError::new(
crate::error::ErrorKind::Validation(format!(
"Score question \"{name}\" has {} criteria; at least two scores are required.",
score.criteria.len()
)),
));
}
}
Question::Noul(_) => {}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn noul_serializes_correctly() {
let q: Question = noul("Is this about billing?").into();
let json = serde_json::to_value(&q).unwrap();
assert_eq!(json["type"], "noul");
assert_eq!(json["instructions"], "Is this about billing?");
assert!(json.get("criteria").is_none());
}
#[test]
fn noul_with_criteria_serializes_correctly() {
let q = noul("?").with_criteria(NoulCriteria {
r#true: Some("yes means this".into()),
r#false: None,
});
let json = serde_json::to_value(&q).unwrap();
assert_eq!(json["criteria"]["true"], "yes means this");
assert!(json["criteria"].get("false").is_none());
}
#[test]
fn choice_serializes_correctly() {
let mut criteria = HashMap::new();
criteria.insert("calm".to_string(), None);
criteria.insert("angry".to_string(), Some("very upset".into()));
let q: Question = choice("Tone?", criteria).into();
let json = serde_json::to_value(&q).unwrap();
assert_eq!(json["type"], "choice");
assert_eq!(json["instructions"], "Tone?");
assert_eq!(json["criteria"]["calm"], serde_json::Value::Null);
assert_eq!(json["criteria"]["angry"], "very upset");
}
#[test]
fn score_serializes_correctly() {
let q: Question = score("Urgency?", vec![Some("low".into()), Some("high".into())]).into();
let json = serde_json::to_value(&q).unwrap();
assert_eq!(json["type"], "score");
assert_eq!(json["instructions"], "Urgency?");
assert_eq!(json["criteria"][0], "low");
assert_eq!(json["criteria"][1], "high");
}
#[test]
fn question_enum_serializes_with_type_tag() {
let q: Question = noul("?").into();
let json = serde_json::to_value(&q).unwrap();
assert_eq!(json["type"], "noul");
}
#[test]
fn validate_rejects_empty_questions() {
let questions = HashMap::new();
let result = validate_questions(&questions);
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("At least one question is required"));
}
#[test]
fn validate_rejects_empty_question_name() {
let mut questions = HashMap::new();
questions.insert("".to_string(), Question::Noul(noul("?")));
let result = validate_questions(&questions);
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("Question names cannot be empty"));
}
#[test]
fn validate_rejects_whitespace_question_name() {
let mut questions = HashMap::new();
questions.insert(" ".to_string(), Question::Noul(noul("?")));
let result = validate_questions(&questions);
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("Question names cannot be empty"));
}
#[test]
fn validate_rejects_score_with_fewer_than_two_criteria() {
let mut questions = HashMap::new();
questions.insert(
"q".to_string(),
Question::Score(score("?", vec![Some("only".into())])),
);
let result = validate_questions(&questions);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("at least two"));
}
#[test]
fn validate_rejects_choice_with_fewer_than_two_criteria() {
let mut questions = HashMap::new();
let mut criteria = HashMap::new();
criteria.insert("only".to_string(), None);
questions.insert("q".to_string(), Question::Choice(choice("?", criteria)));
let result = validate_questions(&questions);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("at least two"));
}
#[test]
fn validate_accepts_valid_questions() {
let mut questions = HashMap::new();
questions.insert("q".to_string(), Question::Noul(noul("?")));
questions.insert(
"s".to_string(),
Question::Score(score("?", vec![Some("low".into()), Some("high".into())])),
);
let mut choice_criteria = HashMap::new();
choice_criteria.insert("a".to_string(), None);
choice_criteria.insert("b".to_string(), None);
questions.insert(
"c".to_string(),
Question::Choice(choice("?", choice_criteria)),
);
assert!(validate_questions(&questions).is_ok());
}
}