zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! What every marketplace verb prints, and the session shows: a [`Doc`] of
//! key/value lines and an optional table, built from hub JSON by pure
//! functions so they can be tested against fixtures.

use colored::Colorize;
use serde_json::Value;

#[derive(Debug, Clone, Default, PartialEq)]
pub struct Table {
    pub headers: Vec<String>,
    pub rows: Vec<Vec<String>>,
}

impl Table {
    pub fn new(headers: &[&str]) -> Self {
        Table {
            headers: headers.iter().map(|h| h.to_string()).collect(),
            rows: Vec::new(),
        }
    }

    /// Column widths: the widest cell (or header) of each column.
    pub fn widths(&self) -> Vec<usize> {
        (0..self.headers.len())
            .map(|i| {
                self.rows
                    .iter()
                    .filter_map(|r| r.get(i))
                    .map(|c| c.chars().count())
                    .chain([self.headers[i].chars().count()])
                    .max()
                    .unwrap_or(0)
            })
            .collect()
    }

    pub fn render(&self) -> String {
        let w = self.widths();
        let line = |cells: &[String]| {
            let last = cells.len().saturating_sub(1);
            cells
                .iter()
                .enumerate()
                .map(|(i, c)| match i == last {
                    true => c.clone(),
                    false => format!("{c:<width$}", width = w[i]),
                })
                .collect::<Vec<_>>()
                .join("  ")
        };
        let mut out = format!("  {}\n", line(&self.headers).bold());
        for r in &self.rows {
            out.push_str(&format!("  {}\n", line(r)));
        }
        out
    }
}

/// One answer: a title, `key  value` lines, a table, and a closing note.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Doc {
    pub kv: Vec<(String, String)>,
    pub table: Option<Table>,
    pub note: Option<String>,
}

impl Doc {
    pub fn kv(pairs: Vec<(&str, String)>) -> Self {
        Doc {
            kv: pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
            ..Default::default()
        }
    }
    pub fn table(t: Table) -> Self {
        Doc {
            table: Some(t),
            ..Default::default()
        }
    }
    pub fn note(n: impl Into<String>) -> Self {
        Doc {
            note: Some(n.into()),
            ..Default::default()
        }
    }
    pub fn with_table(mut self, t: Table) -> Self {
        self.table = Some(t);
        self
    }
    pub fn with_note(mut self, n: impl Into<String>) -> Self {
        self.note = Some(n.into());
        self
    }

    pub fn render(&self) -> String {
        let mut out = String::new();
        let kw = self
            .kv
            .iter()
            .map(|(k, _)| k.chars().count())
            .max()
            .unwrap_or(0);
        for (k, v) in &self.kv {
            out.push_str(&format!("  {}  {v}\n", format!("{k:<kw$}").bold()));
        }
        if let Some(t) = &self.table {
            if !self.kv.is_empty() {
                out.push('\n');
            }
            match t.rows.is_empty() {
                true => out.push_str(&format!("  {}\n", "nothing here yet".dimmed())),
                false => out.push_str(&t.render()),
            }
        }
        if let Some(n) = &self.note {
            out.push_str(&format!("  {n}\n"));
        }
        out
    }
}

/// A string field, `-` when missing or null.
pub fn st(v: &Value, key: &str) -> String {
    match v.get(key) {
        Some(Value::String(s)) if !s.is_empty() => s.clone(),
        Some(Value::Number(n)) => n.to_string(),
        Some(Value::Bool(b)) => b.to_string(),
        _ => "-".into(),
    }
}

/// A numeric field, with `digits` decimals; `-` when missing.
pub fn num(v: &Value, key: &str, digits: usize) -> String {
    match v.get(key).and_then(Value::as_f64) {
        Some(n) => format!("{n:.digits$}"),
        None => "-".into(),
    }
}

/// A date-time as `YYYY-MM-DD HH:MM` (the hub sends ISO 8601).
pub fn when(v: &Value, key: &str) -> String {
    match v.get(key).and_then(Value::as_str) {
        Some(s) if s.len() >= 16 => s[..16].replace('T', " "),
        Some(s) if !s.is_empty() => s.to_string(),
        _ => "-".into(),
    }
}

/// Yen, whole, with thousands separators: `Â¥1,234`.
pub fn yen(n: f64) -> String {
    let neg = n < 0.0;
    let whole = n.abs().round() as u64;
    let digits = whole.to_string();
    let mut out = String::new();
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(c);
    }
    format!("{}Â¥{out}", if neg { "-" } else { "" })
}

/// A yen field; `-` when missing.
pub fn yen_of(v: &Value, key: &str) -> String {
    v.get(key)
        .and_then(Value::as_f64)
        .map(yen)
        .unwrap_or_else(|| "-".into())
}

/// Bytes as `1.5 GB`.
pub fn bytes(n: f64) -> String {
    let units = ["B", "KB", "MB", "GB", "TB"];
    let (mut n, mut i) = (n, 0);
    while n >= 1000.0 && i < units.len() - 1 {
        n /= 1000.0;
        i += 1;
    }
    match i {
        0 => format!("{n:.0} B"),
        _ => format!("{n:.1} {}", units[i]),
    }
}

pub fn bytes_of(v: &Value, key: &str) -> String {
    v.get(key)
        .and_then(Value::as_f64)
        .map(bytes)
        .unwrap_or_else(|| "-".into())
}

/// `s` cut to `max` characters with an ellipsis.
pub fn clip(s: &str, max: usize) -> String {
    match s.chars().count() > max {
        true => format!(
            "{}…",
            s.chars().take(max.saturating_sub(1)).collect::<String>()
        ),
        false => s.to_string(),
    }
}

/// The items of a list answer: a bare array, or `{key: [...]}`.
pub fn items<'a>(v: &'a Value, key: &str) -> &'a [Value] {
    v.as_array()
        .or_else(|| v.get(key).and_then(Value::as_array))
        .map(Vec::as_slice)
        .unwrap_or(&[])
}

/// Any JSON object as `key  value` lines: scalars as they are, lists as
/// their length, nested objects one level down as `outer.inner`. For
/// answers whose shape is the hub's to change.
pub fn flat_doc(v: &Value) -> Doc {
    fn scalar(v: &Value) -> String {
        match v {
            Value::Null => "-".into(),
            Value::String(s) if s.is_empty() => "-".into(),
            Value::String(s) => s.clone(),
            Value::Array(a) => a
                .iter()
                .map(|x| {
                    x.as_str()
                        .map(str::to_string)
                        .unwrap_or_else(|| x.to_string())
                })
                .collect::<Vec<_>>()
                .join(", "),
            other => other.to_string(),
        }
    }
    let mut kv = Vec::new();
    if let Some(o) = v.as_object() {
        for (k, val) in o {
            match val {
                Value::Object(inner) => {
                    for (k2, v2) in inner {
                        if !v2.is_object() {
                            kv.push((format!("{k}.{k2}"), clip(&scalar(v2), 100)));
                        }
                    }
                }
                Value::Array(a) if a.iter().any(|x| x.is_object()) => {
                    kv.push((k.clone(), format!("{} item(s)", a.len())));
                }
                other => kv.push((k.clone(), clip(&scalar(other), 100))),
            }
        }
    }
    Doc {
        kv,
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn yen_groups_thousands_and_keeps_the_sign() {
        assert_eq!(yen(2937749.56), "Â¥2,937,750");
        assert_eq!(yen(-1234.0), "-Â¥1,234");
        assert_eq!(yen(0.0), "Â¥0");
    }

    #[test]
    fn bytes_use_decimal_units() {
        assert_eq!(bytes(18832.0), "18.8 KB");
        assert_eq!(bytes(12.0), "12 B");
        assert_eq!(bytes(1.5e9), "1.5 GB");
    }

    #[test]
    fn missing_fields_read_as_a_dash() {
        let v = json!({"a": "x", "n": null, "d": "2026-11-18T14:00:01.418+00:00"});
        assert_eq!(st(&v, "a"), "x");
        assert_eq!(st(&v, "n"), "-");
        assert_eq!(st(&v, "zz"), "-");
        assert_eq!(when(&v, "d"), "2026-11-18 14:00");
        assert_eq!(num(&v, "zz", 2), "-");
    }

    #[test]
    fn a_table_aligns_every_column_but_the_last() {
        let mut t = Table::new(&["id", "name"]);
        t.rows.push(vec!["a".into(), "one".into()]);
        t.rows.push(vec!["bbbb".into(), "two".into()]);
        assert_eq!(t.widths(), vec![4, 4]);
        let out = t.render();
        assert!(out.contains("a     one"), "{out}");
    }

    #[test]
    fn an_empty_table_says_so() {
        let d = Doc::table(Table::new(&["id"]));
        assert!(d.render().contains("nothing here yet"));
    }

    #[test]
    fn flat_doc_flattens_one_level_and_counts_lists() {
        let d = flat_doc(
            &json!({"a": 1, "b": {"c": "x", "d": {"e": 1}}, "l": [{"x": 1}], "t": ["p", "q"], "n": null}),
        );
        let get = |k: &str| d.kv.iter().find(|(kk, _)| kk == k).map(|(_, v)| v.clone());
        assert_eq!(get("a").as_deref(), Some("1"));
        assert_eq!(get("b.c").as_deref(), Some("x"));
        assert_eq!(get("b.d.e"), None);
        assert_eq!(get("l").as_deref(), Some("1 item(s)"));
        assert_eq!(get("t").as_deref(), Some("p, q"));
        assert_eq!(get("n").as_deref(), Some("-"));
    }

    #[test]
    fn items_reads_a_bare_list_or_a_keyed_one() {
        assert_eq!(items(&json!([1, 2]), "items").len(), 2);
        assert_eq!(items(&json!({"items": [1]}), "items").len(), 1);
        assert_eq!(items(&json!(null), "items").len(), 0);
    }
}