zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Squads (shared groups with a policy, a budget and lent nodes), the
//! template catalogue, and what an endpoint of a template would accept.

use serde_json::{json, Value};

use super::client::{enc, Client, HubError};
use super::fmt::*;
use super::{Fail, Out, Parsed};

fn is_archived(s: &Value) -> bool {
    s["archived"].as_bool() == Some(true)
}

/// The squad's name, marked when it is archived (the hub still lists and
/// shows those, but they take no nodes).
pub fn archived_name(s: &Value) -> String {
    let name = clip(&st(s, "name"), 32);
    match is_archived(s) {
        true => format!("{name} (archived)"),
        false => name,
    }
}

pub fn squads_table(v: &Value) -> Doc {
    let mut t = Table::new(&["ID", "SLUG", "NAME", "KIND", "ROLE", "MEMBERS", "BUDGET/MO"]);
    for s in items(v, "squads") {
        t.rows.push(vec![
            st(s, "id"),
            st(s, "slug"),
            archived_name(s),
            st(s, "kind"),
            st(s, "role"),
            s["members"]
                .as_array()
                .map_or("-".into(), |m| m.len().to_string()),
            yen_of(s, "budget_per_month"),
        ]);
    }
    Doc::table(t)
}

pub fn squad_doc(s: &Value) -> Doc {
    let mut m = Table::new(&["EMAIL", "ROLE", "JOINED"]);
    for x in items(&s["members"], "members") {
        m.rows
            .push(vec![st(x, "email"), st(x, "role"), st(x, "joined")]);
    }
    Doc::kv(vec![
        ("id", st(s, "id")),
        ("slug", st(s, "slug")),
        ("name", st(s, "name")),
        ("purpose", st(s, "purpose")),
        ("kind", st(s, "kind")),
        ("your role", st(s, "role")),
        ("can edit", st(s, "can_edit")),
        ("budget per month", yen_of(s, "budget_per_month")),
        ("price cap per second", num(s, "price_cap_per_second", 4)),
        ("policy revision", st(s, "policy_revision")),
        (
            "grants",
            s["grants"]
                .as_array()
                .map_or("-".into(), |g| g.len().to_string()),
        ),
        ("archived", if is_archived(s) { "yes" } else { "no" }.into()),
    ])
    .with_table(m)
}

pub fn nodes_doc(v: &Value) -> Doc {
    let mut t = Table::new(&["NODE PUBLIC KEY"]);
    for n in items(&v["nodes"], "nodes") {
        t.rows.push(vec![n.as_str().unwrap_or("-").to_string()]);
    }
    Doc::table(t)
}

pub fn invites_table(v: &Value) -> Doc {
    let mut t = Table::new(&["ID", "ROLE", "EMAIL", "USES", "STATUS", "EXPIRES"]);
    for i in items(v, "invites") {
        t.rows.push(vec![
            st(i, "id"),
            st(i, "role"),
            st(i, "email"),
            format!("{}/{}", st(i, "uses"), st(i, "max_uses")),
            st(i, "status"),
            when(i, "expires_at"),
        ]);
    }
    Doc::table(t)
}

/// What a created invite shows: the link is the only time the secret is.
pub fn invite_created_doc(i: &Value) -> Doc {
    Doc::kv(vec![
        ("invite", st(i, "id")),
        ("role", st(i, "role")),
        ("email", st(i, "email")),
        ("expires", when(i, "expires_at")),
        ("emailed", st(i, "emailed")),
        ("link", st(i, "link")),
    ])
    .with_note("the link is shown once; send it to the person you invite")
}

/// Why a nodes call failed: the hub answers 404 "No such squad" for an
/// archived squad, which its list and show routes still return.
pub fn nodes_error(c: &Client, id: &str, name: &str, e: HubError) -> Fail {
    if let HubError::NotFound(_) = e {
        if let Ok(sq) = c.get(&format!("/api/squads/{}", enc(id))) {
            if is_archived(&sq) {
                let label = sq["slug"].as_str().unwrap_or(name);
                return Fail::Usage(format!(
                    "squad {label} is archived; archived squads have no nodes"
                ));
            }
        }
    }
    Fail::Hub(e)
}

/// A squad by id or slug.
pub fn squad_id(c: &Client, r: &str) -> Result<String, Fail> {
    let looks_like_id = r.len() == 36 && r.matches('-').count() == 4;
    if looks_like_id {
        return Ok(r.to_string());
    }
    let all = c.get("/api/squads")?;
    items(&all, "squads")
        .iter()
        .find(|s| s["slug"] == r)
        .and_then(|s| s["id"].as_str().map(str::to_string))
        .ok_or_else(|| Fail::Usage(format!("no squad {r:?} among yours")))
}

/// The policy a squad starts with when `--policy` is not given: its members
/// may process Spaces work.
pub fn default_policy() -> Value {
    json!({
        "Version": "2026-01-01",
        "Statement": [{
            "Sid": "members-process-spaces",
            "Effect": "Allow",
            "Action": "spaces:Process",
            "Resource": "arn:zakuro:spaces:::*"
        }]
    })
}

pub fn create_body(a: &Parsed, policy: Option<Value>) -> Result<Value, Fail> {
    let slug = a.pos.first().ok_or_else(|| {
        Fail::Usage(
            "usage: zc squad create SLUG [--name N] [--purpose P] [--budget YEN] [--policy FILE]"
                .into(),
        )
    })?;
    let budget: f64 = match a.opt("budget") {
        Some(b) => b
            .parse()
            .map_err(|_| Fail::Usage(format!("--budget takes a number, got {b:?}")))?,
        None => 0.0,
    };
    Ok(json!({
        "slug": slug,
        "name": a.opt("name").unwrap_or(slug),
        "purpose": a.opt("purpose").unwrap_or(""),
        "policy": policy.unwrap_or_else(default_policy),
        "budget_per_month": budget,
    }))
}

pub fn invite_body(a: &Parsed) -> Result<Value, Fail> {
    let mut b = json!({});
    if let Some(r) = a.opt("role") {
        b["role"] = json!(r);
    }
    if let Some(e) = a.opt("email") {
        b["email"] = json!(e);
    }
    for (flag, key) in [("uses", "max_uses"), ("hours", "expires_in_hours")] {
        if let Some(n) = a.opt(flag) {
            let n: u64 = n
                .parse()
                .map_err(|_| Fail::Usage(format!("--{flag} takes a whole number, got {n:?}")))?;
            b[key] = json!(n);
        }
    }
    Ok(b)
}

pub fn squad(c: &Client, sub: &str, a: &Parsed) -> Result<Out, Fail> {
    let need = |what: &str| {
        a.pos
            .first()
            .cloned()
            .ok_or_else(|| Fail::Usage(format!("usage: zc squad {sub} SQUAD{what}")))
    };
    match sub {
        "ls" | "list" => {
            let v = c.get("/api/squads")?;
            Ok((v.clone(), squads_table(&v)))
        }
        "public" => {
            let v = c.get("/api/squads/public")?;
            Ok((v.clone(), flat_doc(&v)))
        }
        "show" | "policy" | "usage" | "nodes" | "invites" => {
            let id = squad_id(c, &need("")?)?;
            let path = format!("/api/squads/{}", enc(&id));
            match sub {
                "show" => {
                    let v = c.get(&path)?;
                    Ok((v.clone(), squad_doc(&v)))
                }
                "nodes" => match a.pos.get(1).map(String::as_str) {
                    None => {
                        let v = c
                            .get(&format!("{path}/nodes"))
                            .map_err(|e| nodes_error(c, &id, &need("").unwrap_or_default(), e))?;
                        Ok((v.clone(), nodes_doc(&v)))
                    }
                    Some(verb @ ("add" | "remove")) => {
                        let key = a.pos.get(2).ok_or_else(|| {
                            Fail::Usage(format!("usage: zc squad nodes SQUAD {verb} NODE_PUBKEY"))
                        })?;
                        let body = json!({"node_pubkey": key});
                        let sent = match verb {
                            "add" => c.post(&format!("{path}/nodes"), Some(body)),
                            _ => c.delete(&format!("{path}/nodes"), Some(body)),
                        };
                        let v = sent
                            .map_err(|e| nodes_error(c, &id, &need("").unwrap_or_default(), e))?;
                        let n = v["nodes"].as_array().map_or(0, Vec::len);
                        Ok((
                            v,
                            Doc::note(format!("node {verb} done; the squad now has {n} node(s)")),
                        ))
                    }
                    Some(_) => Err(Fail::Usage(
                        "usage: zc squad nodes SQUAD [add|remove NODE_PUBKEY]".into(),
                    )),
                },
                "invites" => {
                    let v = c.get(&format!("{path}/invites"))?;
                    Ok((v.clone(), invites_table(&v)))
                }
                other => {
                    let v = c.get(&format!("{path}/{other}"))?;
                    Ok((v.clone(), flat_doc(&v)))
                }
            }
        }
        "create" => {
            let policy = match a.opt("policy") {
                Some(f) => {
                    let text = std::fs::read_to_string(f)
                        .map_err(|e| Fail::Usage(format!("--policy {f}: {e}")))?;
                    Some(
                        serde_json::from_str(&text)
                            .map_err(|e| Fail::Usage(format!("--policy {f}: {e}")))?,
                    )
                }
                None => None,
            };
            let v = c.post("/api/squads", Some(create_body(a, policy)?))?;
            let doc = squad_doc(&v);
            Ok((v, doc))
        }
        "invite" => {
            let id = squad_id(
                c,
                &need(" [--role Member|Admin|Owner] [--email E] [--uses N] [--hours N]")?,
            )?;
            let v = c.post(
                &format!("/api/squads/{}/invites", enc(&id)),
                Some(invite_body(a)?),
            )?;
            let doc = invite_created_doc(&v);
            Ok((v, doc))
        }
        "accept" => {
            let token = a
                .pos
                .first()
                .ok_or_else(|| Fail::Usage("usage: zc squad accept TOKEN_OR_LINK".into()))?;
            // A pasted link carries the token after `token=` or the last `/`.
            let token = token
                .rsplit(['=', '/'])
                .next()
                .filter(|t| !t.is_empty())
                .unwrap_or(token);
            let v = c.post("/api/squad-invites/accept", Some(json!({"token": token})))?;
            let note = match v["joined"].as_bool() {
                Some(false) => format!("you were already in {}", st(&v, "name")),
                _ => format!("joined {} as {}", st(&v, "name"), st(&v, "role")),
            };
            Ok((v, Doc::note(note)))
        }
        "leave" => {
            let id = squad_id(c, &need("")?)?;
            let v = c.post(&format!("/api/squads/{}/leave", enc(&id)), None)?;
            Ok((
                v,
                Doc::note("you left the squad; work your nodes already hold finishes and is paid"),
            ))
        }
        _ => Err(Fail::Usage(
            "usage: zc squad ls|public|show|policy|usage|nodes|invites|create|invite|accept|leave"
                .into(),
        )),
    }
}

pub fn templates_table(v: &Value) -> Doc {
    let mut t = Table::new(&[
        "TEMPLATE",
        "NAME",
        "TIER",
        "GPU",
        "MIN VRAM",
        "PRICE/S",
        "DESCRIPTION",
    ]);
    for x in items(v, "templates") {
        t.rows.push(vec![
            st(x, "id"),
            st(x, "name"),
            st(x, "tier"),
            if x["gpu_required"].as_bool() == Some(true) {
                "yes"
            } else {
                "no"
            }
            .into(),
            x["min_vram_gb"]
                .as_u64()
                .map_or("-".into(), |g| format!("{g} GB")),
            num(x, "default_price_per_second", 4),
            clip(&st(x, "description"), 50),
        ]);
    }
    Doc::table(t)
}

pub fn options_doc(v: &Value) -> Doc {
    let mut t = Table::new(&["PLACED ON", "VRAM", "ONLINE", "USABLE", "FROM", "WHY NOT"]);
    let row = |label: String, x: &Value| {
        vec![
            label,
            x["vram_gb"]
                .as_u64()
                .map_or("-".into(), |g| format!("{g} GB")),
            st(x, "online"),
            st(x, "usable"),
            x["price_per_hour"]
                .as_f64()
                .map_or("-".into(), |p| format!("{}/h", yen(p))),
            st(x, "reason"),
        ]
    };
    for x in items(&v["tiers"], "tiers") {
        t.rows.push(row(st(x, "gpu_model"), x));
    }
    if let Some(cpu) = v.get("cpu").filter(|c| c.is_object()) {
        t.rows.push(row("cpu only".into(), cpu));
    }
    Doc::kv(vec![
        ("template", st(v, "template_id")),
        ("needs a gpu", st(v, "requires_gpu")),
        ("min vram", st(v, "min_vram_gb")),
    ])
    .with_table(t)
}

pub fn templates(c: &Client) -> Result<Out, Fail> {
    let v = c.get("/api/templates")?;
    Ok((v.clone(), templates_table(&v)))
}

pub fn endpoint(c: &Client, sub: &str, a: &Parsed) -> Result<Out, Fail> {
    match sub {
        "options" => {
            let t = a
                .pos
                .first()
                .ok_or_else(|| Fail::Usage("usage: zc endpoint options TEMPLATE_ID".into()))?;
            let v = c.get_q("/api/endpoints/options", &[("template_id", t)])?;
            Ok((v.clone(), options_doc(&v)))
        }
        _ => Err(Fail::Usage("usage: zc endpoint options TEMPLATE_ID".into())),
    }
}