use lingara_dialogue_ir::{DialogueIr, Edge, FactValue, limits, predicate, text};
use serde_json::{Map, Value, json};
use crate::dialogue::graph::runner::GraphState;
pub(crate) fn check(ir: &DialogueIr, key: &str, value: &FactValue) -> Result<(), String> {
let Some(decl) = ir.fact(key) else { return Err(format!("no fact `{key}` is declared")) };
if value.fact_type() != decl.kind {
return Err(format!("fact `{key}` is declared {:?}, not {:?}", decl.kind, value.fact_type()));
}
match value {
FactValue::Number(n) if !n.as_f64().is_some_and(f64::is_finite) => Err(format!("fact `{key}` must be a finite number")),
FactValue::String(s) => sendable_text(s).map_err(|why| format!("fact `{key}` {why}")),
_ => Ok(()),
}
}
fn sendable_text(value: &str) -> Result<(), String> {
text::one_line(value).map_err(|fault| fault.describe().to_owned())?;
let n = value.chars().count();
if n > limits::MAX_FACT_STRING_CHARS {
return Err(format!("is {n} characters, more than the turn's {}", limits::MAX_FACT_STRING_CHARS));
}
Ok(())
}
fn sendable<'a>(state: &'a GraphState, key: &str) -> Option<&'a FactValue> {
let value = predicate::value(state.set_facts(), &state.ir().facts, key)?;
match value {
FactValue::String(s) if sendable_text(s).is_err() => None,
_ => Some(value),
}
}
pub(crate) fn turn_fields(state: &GraphState, body: &mut Value) -> Vec<String> {
let checkpoint = state.current();
body["pedagogy"] = json!(state.ir().pedagogy);
body["checkpoint"] = json!({ "id": checkpoint.id, "goal": checkpoint.goal, "may_disclose": checkpoint.may_disclose });
let offered = state.offered();
stance(state, &offered, body);
if !offered.is_empty() {
body["edges"] = offered.iter().map(|edge| json!({ "id": edge.id, "to": edge.to, "when": edge.when })).collect();
}
let facts: Map<String, Value> = checkpoint.may_disclose.iter().filter_map(|key| sendable(state, key).map(|value| (key.clone(), json!(value)))).collect();
if !facts.is_empty() {
body["facts"] = Value::Object(facts);
}
offered.iter().map(|edge| edge.id.clone()).collect()
}
fn stance(state: &GraphState, offered: &[&Edge], body: &mut Value) {
if let Some(disposition) = &state.npc().disposition {
body["npc"]["disposition"] = json!(disposition);
}
let steer = state.current().steer_to.as_ref().and_then(|id| offered.iter().find(|edge| &edge.id == id));
if let Some(when) = steer.and_then(|edge| edge.when.as_ref()) {
body["checkpoint"]["steer"] = json!(when);
}
}