zc2 0.0.38

P2P compute broker with credit-based billing, WAL, and broker mesh support
use super::{centered, fg, selected, spinner, INK3, NUM, SPLIT_W};
use crate::session::app::App;
use crate::session::model::{price_text, MeshNode, MeshWorker, RowRef};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Cell, Clear, Paragraph, Row, Table, TableState};
use ratatui::Frame;

/// A node row. The address is not a column — at the split it would crowd
/// out the names — it is the first line of the detail pane.
fn node_cells(n: &MeshNode, open: bool) -> Vec<Cell<'static>> {
    let mark = if n.workers.is_empty() {
        " "
    } else if open {
        "▾"
    } else {
        "▸"
    };
    if n.workers.is_empty() {
        return vec![
            Cell::from(format!("{mark} {}  · no worker detail", n.label())).style(fg(INK3)),
            Cell::from(""),
            Cell::from(""),
            Cell::from(""),
            Cell::from(""),
            Cell::from(""),
        ];
    }
    let price = match n.price_range() {
        Some((lo, hi)) if lo == hi => price_text(lo),
        Some((lo, hi)) => format!("{}–{}", price_text(lo), price_text(hi)),
        None => String::new(),
    };
    let count = match n.workers.len() {
        1 => "1 worker".to_string(),
        k => format!("{k} workers"),
    };
    vec![
        Cell::from(format!("{mark} {}", n.label())),
        Cell::from(count).style(fg(INK3)),
        Cell::from(format!("{:.0}", n.total_cpus())),
        Cell::from(n.total_gpus().to_string()),
        Cell::from(format!("{:.0}G", n.total_mem_gib())),
        Cell::from(price).style(fg(NUM)),
    ]
}

fn worker_cells(w: &MeshWorker) -> Vec<Cell<'static>> {
    vec![
        Cell::from(format!("    {}", w.name)),
        Cell::from(w.status.clone()).style(fg(INK3)),
        Cell::from(format!("{:.0}", w.cpus)),
        Cell::from(w.gpus.to_string()),
        Cell::from(format!("{:.0}G", w.mem_total_gib)),
        Cell::from(price_text(w.price_per_hour)),
    ]
}

fn list(f: &mut Frame, area: Rect, app: &App) {
    let Some(m) = &app.mesh else {
        f.render_widget(
            Paragraph::new(format!(" {} loading the mesh…", spinner(app))).style(fg(INK3)),
            area,
        );
        return;
    };
    let rows: Vec<Row> = app
        .rows()
        .iter()
        .map(|r| match *r {
            RowRef::Node(i) => {
                let n = &m.nodes[i];
                let open = app.expanded.contains(&n.fp) || !app.filter.is_empty();
                Row::new(node_cells(n, open))
            }
            RowRef::Worker(i, j) => Row::new(worker_cells(&m.nodes[i].workers[j])),
        })
        .collect();
    let mut title = format!(
        " mesh · {} nodes · sort {} ",
        m.nodes.len(),
        app.sort.title()
    );
    if !app.filter.is_empty() || app.filtering {
        title.push_str(&format!("· /{} ", app.filter));
    }
    let mut foot: Vec<String> = Vec::new();
    if let Some(why) = &m.local_only {
        foot.push(format!("this machine only — {why}"));
    }
    if let Some(a) = m.as_of_secs {
        foot.push(format!("brokers as of {a}s ago"));
    }
    if m.unreachable > 0 {
        foot.push(format!("{} unreachable", m.unreachable));
    }
    if let Some(e) = &m.workers_error {
        foot.push(e.clone());
    }
    let block = Block::bordered()
        .border_style(fg(INK3))
        .title(title)
        .title_bottom(format!(" {} ", foot.join(" · ")));
    let table = Table::new(
        rows,
        [
            Constraint::Fill(1),
            Constraint::Length(9),
            Constraint::Length(4),
            Constraint::Length(4),
            Constraint::Length(5),
            Constraint::Length(7),
        ],
    )
    .header(Row::new(["NODE / WORKER", "STATUS", "CPUs", "GPUs", "MEM", "PRICE"]).style(fg(INK3)))
    .row_highlight_style(selected())
    .block(block);
    let mut state = TableState::default();
    state.select((!app.rows().is_empty()).then_some(app.mesh_sel));
    f.render_stateful_widget(table, area, &mut state);
}

fn detail_lines(app: &App) -> Vec<Line<'static>> {
    let (Some(m), Some(r)) = (&app.mesh, app.selected_row()) else {
        return vec![Line::from(Span::styled("nothing selected", fg(INK3)))];
    };
    let kv = |k: &str, v: String| {
        Line::from(vec![
            Span::styled(format!("{k:<12}"), fg(INK3)),
            Span::raw(v),
        ])
    };
    match r {
        RowRef::Node(i) => {
            let n = &m.nodes[i];
            vec![
                kv("Address", n.address()),
                kv("Name", n.label()),
                kv("Workers", n.workers.len().to_string()),
                kv("CPUs", format!("{:.0}", n.total_cpus())),
                kv("GPUs", n.total_gpus().to_string()),
                kv("Memory", format!("{:.0} GiB", n.total_mem_gib())),
                Line::default(),
                Line::from(Span::styled("c copy address · y copy SDK line", fg(INK3))),
            ]
        }
        RowRef::Worker(i, j) => {
            let n = &m.nodes[i];
            let w = &n.workers[j];
            let opt = |o: &Option<String>| o.clone().unwrap_or_else(|| "-".into());
            vec![
                kv("Address", n.address()),
                kv("Worker", w.name.clone()),
                kv("Status", w.status.clone()),
                kv("CPU", format!("{:.0} × {}", w.cpus, opt(&w.cpu_model))),
                kv(
                    "GPU",
                    match w.gpus {
                        0 => "none".into(),
                        g => format!(
                            "{g} × {} {}",
                            opt(&w.gpu_model),
                            w.gpu_vram_gb.map(|v| format!("{v} GB")).unwrap_or_default()
                        ),
                    },
                ),
                kv(
                    "Memory",
                    format!("{:.1} of {:.0} GiB free", w.mem_avail_gib, w.mem_total_gib),
                ),
                kv(
                    "Storage",
                    w.storage_gb
                        .map(|s| format!("{s} GB"))
                        .unwrap_or_else(|| "-".into()),
                ),
                kv("Python", opt(&w.python)),
                kv("Price", format!("{} zkcr/h", price_text(w.price_per_hour))),
                kv(
                    "Models",
                    match w.served_models.is_empty() {
                        true => "-".into(),
                        false => w.served_models.join(", "),
                    },
                ),
                kv(
                    "Requests",
                    format!("{} in 5h · {} in 1w", w.requests_5h, w.requests_1w),
                ),
            ]
        }
    }
}

fn detail(f: &mut Frame, area: Rect, app: &App) {
    f.render_widget(
        Paragraph::new(detail_lines(app))
            .block(Block::bordered().border_style(fg(INK3)).title(" detail ")),
        area,
    );
}

pub fn render(f: &mut Frame, area: Rect, app: &App) {
    if area.width >= SPLIT_W {
        // The list gets the larger share: worker names are long and the
        // detail lines are short.
        let [l, r] = Layout::horizontal([Constraint::Percentage(60), Constraint::Percentage(40)])
            .areas(area);
        list(f, l, app);
        detail(f, r, app);
        return;
    }
    list(f, area, app);
    if app.detail {
        let r = centered(area, area.width.saturating_sub(8), 15);
        f.render_widget(Clear, r);
        detail(f, r, app);
    }
}