use std::{collections::BTreeMap, time::Duration};
use rho_sdk::{HostInputResponse, HostQuestion};
use serde::Deserialize;
use serde_json::{json, Value};
use super::{question_id, QuestionnaireRequest, RawQuestionnaireQuestion};
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct LegacyOnTimeout {
answers: BTreeMap<String, Value>,
#[serde(default)]
reason: Option<String>,
}
impl LegacyOnTimeout {
pub(super) fn apply(
self,
questions: &mut [RawQuestionnaireQuestion],
) -> Result<Option<String>, String> {
for (id, answer) in self.answers {
let question = questions
.iter_mut()
.enumerate()
.find(|(index, question)| question_id(*index, question.id.as_deref()) == id)
.map(|(_, question)| question)
.ok_or_else(|| format!("on_timeout.answers names unknown question '{id}'"))?;
if question.if_unanswered.is_some() {
return Err(format!(
"question '{id}' has both if_unanswered and an on_timeout answer; give only if_unanswered"
));
}
question.if_unanswered = Some(answer);
}
Ok(self.reason)
}
}
impl QuestionnaireRequest {
pub fn fallback(&self) -> Option<HostInputResponse> {
let offered = self
.questions
.iter()
.any(|question| question.if_unanswered.is_some());
let covered = self
.questions
.iter()
.all(|question| !question.required || question.if_unanswered.is_some());
(offered && covered).then(|| {
self.questions
.iter()
.filter_map(|question| Some((&question.id, question.if_unanswered.clone()?)))
.fold(HostInputResponse::new(), |response, (id, values)| {
response.answer(id, values)
})
})
}
}
pub(super) fn answer_values(answer: Value) -> Vec<String> {
match answer {
Value::String(value) => vec![value],
Value::Array(values) => values
.into_iter()
.filter_map(|value| match value {
Value::String(value) => Some(value),
_ => None,
})
.collect(),
Value::Null | Value::Bool(_) | Value::Number(_) | Value::Object(_) => Vec::new(),
}
}
pub fn fallback_summary(
questions: &[HostQuestion],
answers: &BTreeMap<String, Vec<String>>,
) -> String {
let labels = |question: &HostQuestion, values: &[String]| {
if values.is_empty() {
return "none".to_owned();
}
values
.iter()
.map(|value| {
question
.choices()
.iter()
.find(|choice| choice.value() == value)
.map_or(value.as_str(), |choice| choice.label())
})
.collect::<Vec<_>>()
.join(", ")
};
let answered: Vec<_> = questions
.iter()
.filter_map(|question| Some((question, answers.get(question.id())?)))
.collect();
match answered.as_slice() {
[] => "no answers".to_owned(),
[(question, values)] => labels(question, values),
_ => answered
.iter()
.map(|(question, values)| {
let name = question.header().unwrap_or(question.id());
format!("{name}: {}", labels(question, values))
})
.collect::<Vec<_>>()
.join("; "),
}
}
pub(super) fn description(after: Duration) -> String {
let after = human_duration(after);
format!(
"Decide each time whether you could carry on without the user. If you could carry on with a sensible answer, give each question an if_unanswered and the form an assumption; the form expires after {after} and you continue with those answers. Leave them out only when you truly can't proceed without the user; the form then waits. Never give if_unanswered for approvals, permissions, destructive actions, purchases, or other authorization."
)
}
pub(super) fn assumption_schema() -> Value {
json!({
"type": "string",
"description": "With if_unanswered: what you're going with, in one short line the user sees while the form waits, e.g. \"carrying on with nextest; say otherwise anytime\"."
})
}
pub(super) fn if_unanswered_schema() -> Value {
json!({
"description": "Your answer if the user doesn't answer in time, shaped like an answer: a choice label, a list of labels for multi_select, true or false for confirm.",
"oneOf": [
{ "type": "string" },
{ "type": "boolean" },
{ "type": "array", "items": { "type": "string" } }
]
})
}
fn human_duration(after: Duration) -> String {
let (count, unit) = match after.as_secs() {
seconds if seconds >= 3600 && seconds.is_multiple_of(3600) => (seconds / 3600, "hour"),
seconds if seconds >= 60 && seconds.is_multiple_of(60) => (seconds / 60, "minute"),
seconds => (seconds, "second"),
};
let plural = if count == 1 { "" } else { "s" };
format!("{count} {unit}{plural}")
}