zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `zc earnings [--json]` (ADR ZC-0025 ยง6): what this node earned today, over
//! the last 7 days and this month (the hub's provider ledger, through the
//! agent's `/v2/ledger`), next to what only the node knows: how much of the
//! budget was used, how long it sat eligible and idle, and what it refused and
//! why (the broker's `revenue.json`, through the agent's `/v2/summary`).

use chrono::{Datelike, NaiveDate};
use serde_json::{json, Value};

/// Earned today, over the last 7 days (today included) and in the calendar
/// month of `today`, from the hub's `by_day` rows (`{"day": "YYYY-MM-DD",
/// "earned": yen}`).
pub fn periods(by_day: &[Value], today: NaiveDate) -> (f64, f64, f64) {
    let (mut day, mut week, mut month) = (0.0, 0.0, 0.0);
    for g in by_day {
        let Some(d) = g["day"]
            .as_str()
            .and_then(|d| NaiveDate::parse_from_str(d, "%Y-%m-%d").ok())
        else {
            continue;
        };
        let earned = g["earned"].as_f64().unwrap_or(0.0);
        if d == today {
            day += earned;
        }
        let age = (today - d).num_days();
        if (0..7).contains(&age) {
            week += earned;
        }
        if d.year() == today.year() && d.month() == today.month() && d <= today {
            month += earned;
        }
    }
    (day, week, month)
}

fn hms(secs: f64) -> String {
    let s = secs.max(0.0).round() as u64;
    match (s / 3600, (s % 3600) / 60) {
        (0, 0) => format!("{s}s"),
        (0, m) => format!("{m}m"),
        (h, m) => format!("{h}h {m:02}m"),
    }
}

/// The report: the earned figures (or why they are missing) and the node's
/// own revenue object.
pub fn report(ledger: Result<Value, String>, revenue: Option<Value>, today: NaiveDate) -> Value {
    let earned = match &ledger {
        Ok(v) => {
            let rows = v["groups"].as_array().cloned().unwrap_or_default();
            let (d, w, m) = periods(&rows, today);
            json!({"unit": "jpy", "today": d, "week": w, "month": m})
        }
        Err(e) => json!({"unit": "jpy", "unavailable": e}),
    };
    let rev = revenue.unwrap_or(Value::Null);
    json!({
        "earned": earned,
        "utilisation": rev["utilisation"],
        "eligible_idle_seconds": rev["eligible_idle_seconds"],
        "eligible_idle_by_source": rev["eligible_idle_by_source"],
        "refusals": rev["refusals"],
        "sharing_allowed": rev["sharing_allowed"],
        "capacity": rev["capacity"],
        "revenue_available": !rev.is_null(),
    })
}

pub fn render(r: &Value) -> String {
    let mut out = String::new();
    let e = &r["earned"];
    match e["unavailable"].as_str() {
        Some(why) => out += &format!("earned (yen)    unavailable: {why}\n"),
        None => {
            out += &format!(
                "earned (yen)    today {:.2}   7 days {:.2}   month {:.2}\n",
                e["today"].as_f64().unwrap_or(0.0),
                e["week"].as_f64().unwrap_or(0.0),
                e["month"].as_f64().unwrap_or(0.0)
            );
        }
    }
    if r["revenue_available"] != true {
        out += "node figures    unavailable: the broker has not reported yet (is it running?)\n";
        return out;
    }
    let pct = |v: &Value| format!("{:.0}%", v.as_f64().unwrap_or(0.0) * 100.0);
    out += &format!(
        "utilisation     now {}   average {} (of the budget, since the broker started)\n",
        pct(&r["utilisation"]["now"]),
        pct(&r["utilisation"]["avg"])
    );
    let idle = r["eligible_idle_seconds"].as_f64().unwrap_or(0.0);
    out += &format!("eligible idle   {}", hms(idle));
    if let Some(m) = r["eligible_idle_by_source"]
        .as_object()
        .filter(|m| !m.is_empty())
    {
        let parts: Vec<String> = m
            .iter()
            .map(|(k, v)| format!("{k} {}", hms(v.as_f64().unwrap_or(0.0))))
            .collect();
        out += &format!(" ({})", parts.join(", "));
    }
    out += "\n";
    let refused: Vec<String> = r["refusals"]
        .as_object()
        .map(|m| {
            m.iter()
                .filter(|(_, v)| v.as_u64().unwrap_or(0) > 0)
                .map(|(k, v)| format!("{k} {}", v.as_u64().unwrap_or(0)))
                .collect()
        })
        .unwrap_or_default();
    out += &format!(
        "refused         {}\n",
        if refused.is_empty() {
            "nothing".to_string()
        } else {
            refused.join(", ")
        }
    );
    if r["sharing_allowed"] == false {
        out += "                sharing is closed right now (policy: squads, price or schedule)\n";
    }
    out
}

/// What the node says, preferring the agent and falling back to the file the
/// broker mirrors next to it.
fn node_revenue(summary: Option<Value>) -> Option<Value> {
    summary
        .and_then(|s| s.get("revenue").cloned())
        .filter(|v| !v.is_null())
        .or_else(|| {
            crate::credentials::dir().and_then(|d| crate::broker::revenue::read_snapshot(&d))
        })
}

pub fn run(args: &[String], json_out: bool) -> i32 {
    if let Some(a) = args.iter().find(|a| a.as_str() != "--json") {
        eprintln!("zc: unknown argument {a:?}\nusage: zc earnings [--json]");
        return 2;
    }
    let today = chrono::Local::now().date_naive();
    let from = std::cmp::min(
        today.with_day(1).unwrap_or(today),
        today - chrono::Duration::days(6),
    );
    #[cfg(unix)]
    let (ledger, summary) = match crate::agent::client::AgentClient::running() {
        Some(c) => (
            c.get(
                &format!(
                    "/v2/ledger?by=day&from={}&to={}",
                    from.format("%Y-%m-%d"),
                    today.format("%Y-%m-%d")
                ),
                std::time::Duration::from_secs(20),
            ),
            c.get("/v2/summary", std::time::Duration::from_secs(10)).ok(),
        ),
        None => (
            Err("the hub's ledger comes through the zc agent: start it with `zc agent run` (or the app)".to_string()),
            None,
        ),
    };
    #[cfg(not(unix))]
    let (ledger, summary): (Result<Value, String>, Option<Value>) = {
        let _ = from;
        (
            Err("zc earnings needs the zc agent, not built on this platform".to_string()),
            None,
        )
    };
    let r = report(ledger, node_revenue(summary), today);
    if json_out {
        println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
    } else {
        print!("{}", render(&r));
    }
    0
}

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

    fn d(s: &str) -> NaiveDate {
        NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
    }

    fn rows() -> Vec<Value> {
        vec![
            json!({"day": "2026-10-30", "earned": 100.0}),
            json!({"day": "2026-11-03", "earned": 10.0}),
            json!({"day": "2026-11-05", "earned": 5.0}),
            json!({"day": "2026-11-10", "earned": 2.5}),
            json!({"day": "garbage", "earned": 99.0}),
        ]
    }

    #[test]
    fn today_week_and_month_come_from_the_daily_rows() {
        let (day, week, month) = periods(&rows(), d("2026-11-10"));
        assert_eq!(day, 2.5);
        // 11-04 .. 11-10: the 5th and the 10th, not the 3rd.
        assert_eq!(week, 7.5);
        // November only: the 30 October row is last month's.
        assert_eq!(month, 17.5);
    }

    #[test]
    fn the_report_carries_the_node_side_and_says_when_the_ledger_is_missing() {
        let rev = json!({
            "utilisation": {"now": 0.5, "avg": 0.25},
            "eligible_idle_seconds": 4320.0,
            "eligible_idle_by_source": {"spaces_lease": 4320.0},
            "refusals": {"budget": 3, "price": 0, "squad": 0, "workload": 0, "schedule": 0},
            "sharing_allowed": true,
        });
        let ok = report(
            Ok(json!({"groups": [{"day": "2026-11-10", "earned": 2.5}]})),
            Some(rev.clone()),
            d("2026-11-10"),
        );
        assert_eq!(ok["earned"]["today"], 2.5);
        assert_eq!(ok["eligible_idle_seconds"], 4320.0);
        let text = render(&ok);
        assert!(text.contains("today 2.50"), "{text}");
        assert!(text.contains("average 25%"), "{text}");
        assert!(text.contains("1h 12m (spaces_lease 1h 12m)"), "{text}");
        assert!(text.contains("refused         budget 3"), "{text}");
        assert!(
            !text.contains("price 0"),
            "zero refusals stay quiet: {text}"
        );

        let down = report(Err("no agent".into()), None, d("2026-11-10"));
        assert_eq!(down["earned"]["unavailable"], "no agent");
        assert_eq!(down["revenue_available"], false);
        let text = render(&down);
        assert!(text.contains("unavailable: no agent"), "{text}");
        assert!(text.contains("broker has not reported"), "{text}");
    }

    #[test]
    fn a_closed_node_says_so() {
        let rev = json!({"sharing_allowed": false, "refusals": {}, "utilisation": {}});
        let r = report(Err("x".into()), Some(rev), d("2026-11-10"));
        assert!(render(&r).contains("sharing is closed"));
    }

    #[test]
    fn durations_read_as_a_person_would() {
        assert_eq!(hms(0.0), "0s");
        assert_eq!(hms(45.0), "45s");
        assert_eq!(hms(300.0), "5m");
        assert_eq!(hms(3.0 * 3600.0 + 5.0 * 60.0), "3h 05m");
    }

    #[test]
    fn unknown_arguments_are_refused() {
        assert_eq!(run(&["--nope".to_string()], false), 2);
    }
}