use serde_json::{Value, json};
use vta_sdk::error::VtaError;
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;
use crate::render::{BOLD, CYAN, DIM, GREEN, RESET, YELLOW, is_json_output, print_json};
type CmdResult = Result<(), Box<dyn std::error::Error>>;
fn local_code(e: &VtaError) -> Option<&str> {
e.rejection_code()
.map(|c| c.rsplit_once(':').map_or(c, |(_, l)| l))
}
fn fix_for(code: &str, context: &str) -> Option<String> {
Some(match code {
"syncOff" => format!(
"Answers come from the synced calendar. Turn reading on first:\n \
pnm calendar settings update --context {context} --sync on"
),
"hostUnknown" => format!(
"`--host` must be a persona your VTA holds in this context. List them with:\n \
pnm persona list --context {context}"
),
"inviteeInvalid" => "Invite only your contacts, each once, and never the host itself. \
File a contact with `pnm persona contact put` first."
.to_string(),
"alreadyClosed" => "The request is already closed; make a new one to ask again:\n \
pnm findtime create …"
.to_string(),
"noMatchingProtocol" => "The invited identifier and the host share no transport, so \
nothing was sent. The identifier's DID document has to advertise a transport the \
host also does."
.to_string(),
"hostUnreachable" => "The host did not answer. Run the same command again: an answer \
resends the same document, so the host sees it once."
.to_string(),
"notFound" => format!(
"Nothing by that identifier is held in {context}. List what is:\n \
pnm findtime list --context {context}\n pnm findtime invited --context {context}"
),
_ => return None,
})
}
async fn call(
client: &VtaClient,
uri: &str,
payload: Value,
context: &str,
timeout: u64,
) -> Result<Value, Box<dyn std::error::Error>> {
match client.dispatch_trust_task(uri, payload, timeout).await {
Ok(v) => Ok(v),
Err(e) => match local_code(&e).and_then(|c| fix_for(c, context)) {
Some(fix) => Err(format!("{e}\n {fix}").into()),
None => Err(Box::new(e)),
},
}
}
fn slot_of(spec: &str, zone: &str, duration: &str) -> Result<Value, Box<dyn std::error::Error>> {
let (id, start) = spec
.split_once('=')
.ok_or_else(|| format!("`{spec}`: expected <id>=<YYYY-MM-DDTHH:MM>"))?;
let start = if start.len() == 16 {
format!("{start}:00")
} else {
start.to_string()
};
Ok(json!({ "slotId": id, "when": { "start": start, "timeZone": zone, "duration": duration } }))
}
fn answer_of(spec: &str) -> Result<Value, Box<dyn std::error::Error>> {
let (id, choice) = spec
.split_once('=')
.ok_or_else(|| format!("`{spec}`: expected <id>=yes|if-need-be|no"))?;
let choice = match choice {
"yes" => "yes",
"if-need-be" | "ifNeedBe" | "maybe" => "ifNeedBe",
"no" => "no",
other => return Err(format!("`{other}`: expected yes, if-need-be or no").into()),
};
Ok(json!({ "slotId": id, "choice": choice }))
}
pub struct CreateOptions {
pub context: String,
pub host: String,
pub title: String,
pub description: Option<String>,
pub voters: String,
pub slots: Vec<String>,
pub time_zone: String,
pub duration: String,
pub invitees: Vec<String>,
pub closes_at: Option<String>,
}
fn print_request(r: &Value) {
println!(
"{BOLD}{}{RESET} {DIM}{} · {} · voters {}{RESET}",
r["title"].as_str().unwrap_or_default(),
r["requestId"].as_str().unwrap_or_default(),
r["state"].as_str().unwrap_or_default(),
r["voters"].as_str().unwrap_or_default(),
);
let tallies = r["tallies"].as_array().cloned().unwrap_or_default();
for s in r["slots"].as_array().cloned().unwrap_or_default() {
let id = s["slotId"].as_str().unwrap_or_default();
let t = tallies
.iter()
.find(|t| t["slotId"] == id)
.cloned()
.unwrap_or(Value::Null);
let chosen = if r["chosenSlotId"] == id {
format!(" {GREEN}chosen{RESET}")
} else {
String::new()
};
println!(
" {CYAN}{id}{RESET} {} {} {GREEN}{} yes{RESET} · {YELLOW}{} if need be{RESET} · {} no{chosen}",
s["when"]["start"].as_str().unwrap_or_default(),
s["when"]["timeZone"].as_str().unwrap_or_default(),
t["yes"].as_u64().unwrap_or(0),
t["ifNeedBe"].as_u64().unwrap_or(0),
t["no"].as_u64().unwrap_or(0),
);
for a in t["answers"].as_array().cloned().unwrap_or_default() {
let who = a["displayName"]
.as_str()
.or_else(|| a["invitee"].as_str())
.unwrap_or("someone");
println!(
" {DIM}{who}: {}{RESET}",
a["choice"].as_str().unwrap_or_default()
);
}
}
if let Some(e) = r["eventId"].as_str() {
println!(" {DIM}draft event {e} — publish and invite with `pnm events …`{RESET}");
}
if let Some(mine) = r["myAnswers"].as_array() {
let by = r["myAnswersBy"].as_str().unwrap_or("you");
let list: Vec<String> = mine
.iter()
.map(|a| {
format!(
"{}={}",
a["slotId"].as_str().unwrap_or_default(),
a["choice"].as_str().unwrap_or_default()
)
})
.collect();
println!(" {DIM}your answers ({by}): {}{RESET}", list.join(", "));
}
}
pub async fn cmd_findtime_create(client: &VtaClient, o: &CreateOptions) -> CmdResult {
let slots = o
.slots
.iter()
.map(|s| slot_of(s, &o.time_zone, &o.duration))
.collect::<Result<Vec<_>, _>>()?;
let mut req = json!({
"contextId": o.context,
"host": o.host,
"title": o.title,
"voters": o.voters,
"slots": slots,
"invitees": o.invitees,
});
if let Some(d) = &o.description {
req["description"] = json!(d);
}
if let Some(c) = &o.closes_at {
req["closesAt"] = json!(c);
}
let resp = call(
client,
tt::TASK_VTA_FINDTIME_CREATE_0_1,
req,
&o.context,
20,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
println!(
"{GREEN}\u{2713}{RESET} Asked {} contact(s). Each is told by a notification sent as the host.",
o.invitees.len()
);
print_request(&resp["request"]);
Ok(())
}
pub async fn cmd_findtime_show(client: &VtaClient, context: &str, request_id: &str) -> CmdResult {
let resp = call(
client,
tt::TASK_VTA_FINDTIME_SHOW_0_1,
json!({ "contextId": context, "requestId": request_id }),
context,
20,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
print_request(&resp["request"]);
Ok(())
}
pub async fn cmd_findtime_list(
client: &VtaClient,
context: &str,
state: Option<&str>,
) -> CmdResult {
let mut req = json!({ "contextId": context });
if let Some(s) = state {
req["state"] = json!(s);
}
let resp = call(client, tt::TASK_VTA_FINDTIME_LIST_0_1, req, context, 20).await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
let items = resp["requests"].as_array().cloned().unwrap_or_default();
if items.is_empty() {
println!("{DIM}No requests to find a time in {context}.{RESET}");
}
for r in &items {
print_request(r);
}
Ok(())
}
pub async fn cmd_findtime_close(
client: &VtaClient,
context: &str,
request_id: &str,
chosen: Option<&str>,
) -> CmdResult {
let mut req = json!({ "contextId": context, "requestId": request_id });
if let Some(c) = chosen {
req["chosenSlotId"] = json!(c);
}
let resp = call(client, tt::TASK_VTA_FINDTIME_CLOSE_0_1, req, context, 20).await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
println!("{GREEN}\u{2713}{RESET} Closed; every invitee's notification is withdrawn.");
print_request(&resp["request"]);
Ok(())
}
pub async fn cmd_findtime_delete(client: &VtaClient, context: &str, request_id: &str) -> CmdResult {
let resp = call(
client,
tt::TASK_VTA_FINDTIME_DELETE_0_1,
json!({ "contextId": context, "requestId": request_id }),
context,
20,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
println!("{GREEN}\u{2713}{RESET} Deleted, with its answers.");
Ok(())
}
pub async fn cmd_findtime_invited(
client: &VtaClient,
context: &str,
status: Option<&str>,
) -> CmdResult {
let mut req = json!({ "contextId": context });
if let Some(s) = status {
req["status"] = json!(s);
}
let resp = call(
client,
tt::TASK_VTA_FINDTIME_INVITED_LIST_0_1,
req,
context,
20,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
let items = resp["requests"].as_array().cloned().unwrap_or_default();
if items.is_empty() {
println!("{DIM}No requests to find a time held in {context}.{RESET}");
}
for h in items {
println!(
"{BOLD}{}{RESET} from {CYAN}{}{RESET} — {}, answered by {}",
h["requestId"].as_str().unwrap_or_default(),
h["host"].as_str().unwrap_or_default(),
h["status"].as_str().unwrap_or_default(),
h["answeredBy"].as_str().unwrap_or_default(),
);
println!(
" {DIM}to {}{RESET}",
h["invited"].as_str().unwrap_or_default()
);
}
Ok(())
}
pub async fn cmd_findtime_read(
client: &VtaClient,
context: &str,
host: &str,
request_id: &str,
) -> CmdResult {
let resp = call(
client,
tt::TASK_VTA_FINDTIME_INVITED_SHOW_0_1,
json!({ "contextId": context, "host": host, "requestId": request_id }),
context,
60,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
print_request(&resp["request"]);
Ok(())
}
pub async fn cmd_findtime_answer(
client: &VtaClient,
context: &str,
host: &str,
request_id: &str,
answers: &[String],
display_name: Option<&str>,
) -> CmdResult {
let answers = answers
.iter()
.map(|a| answer_of(a))
.collect::<Result<Vec<_>, _>>()?;
let mut req = json!({
"contextId": context, "host": host, "requestId": request_id, "answers": answers,
});
if let Some(n) = display_name {
req["displayName"] = json!(n);
}
let resp = call(
client,
tt::TASK_VTA_FINDTIME_INVITED_ANSWER_0_1,
req,
context,
60,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
println!("{GREEN}\u{2713}{RESET} Answered. Your VTA answers this request for you no more.");
print_request(&resp["request"]);
Ok(())
}
pub async fn cmd_findtime_auto_show(client: &VtaClient, context: &str) -> CmdResult {
let resp = call(
client,
tt::TASK_VTA_FINDTIME_SETTINGS_SHOW_0_1,
json!({ "contextId": context }),
context,
20,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
let choices = resp["choices"].as_array().cloned().unwrap_or_default();
if choices.is_empty() {
println!(
"{DIM}Your VTA answers nobody's requests to find a time in {context}. Turn it on with\n \
pnm findtime auto set --context {context} --host <did> --on{RESET}"
);
}
for c in choices {
let on = c["enabled"] == true;
println!(
" {}{}{RESET} {}",
if on { GREEN } else { DIM },
if on { "answers" } else { "off" },
c["host"].as_str().unwrap_or_default()
);
}
Ok(())
}
pub async fn cmd_findtime_auto_set(
client: &VtaClient,
context: &str,
host: &str,
enabled: bool,
also_count: &[String],
) -> CmdResult {
let mut req = json!({ "contextId": context, "host": host, "enabled": enabled });
if !also_count.is_empty() {
req["alsoCount"] = json!(also_count);
}
let resp = call(
client,
tt::TASK_VTA_FINDTIME_SETTINGS_SET_0_1,
req,
context,
60,
)
.await?;
if is_json_output() {
return Ok(print_json(&resp)?);
}
if enabled {
println!(
"{GREEN}\u{2713}{RESET} Your VTA will answer this host's requests from your calendar, \
one word per time. Answering one yourself always wins."
);
} else {
println!(
"{GREEN}\u{2713}{RESET} Your VTA no longer answers this host's requests; answers \
already given stand."
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_slot_and_an_answer_from_the_command_line() {
let s = slot_of("sat-am=2026-12-05T10:00", "Europe/London", "PT1H").unwrap();
assert_eq!(s["when"]["start"], "2026-12-05T10:00:00");
assert_eq!(s["slotId"], "sat-am");
assert!(slot_of("nope", "Etc/UTC", "PT1H").is_err());
assert_eq!(
answer_of("sat-am=if-need-be").unwrap()["choice"],
"ifNeedBe"
);
assert!(answer_of("sat-am=perhaps").is_err());
}
}