zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The Models, Jobs, Envs and Spaces tabs: the feed's table, and at the
//! split width the selected row in full beside it. Account's usage panel
//! reads the same feeds.

use super::{fg, selected, spinner, INK3, LIVE, NUM, SPLIT_W, WARN};
use crate::market::fmt::Table as Data;
use crate::session::app::{App, Tab};
use crate::session::market::{FeedId, FeedState};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Cell, Paragraph, Row, Table, TableState, Wrap};
use ratatui::Frame;

/// Columns the list leaves to the detail pane: a 36-character id crowds out
/// the names.
const DETAIL_ONLY: &[&str] = &["ID"];

fn title(tab: Tab) -> &'static str {
    match tab {
        Tab::Models => "models",
        Tab::Jobs => "La Forge jobs",
        Tab::Envs => "environments",
        Tab::Spaces => "spaces",
        _ => "",
    }
}

fn empty_hint(tab: Tab) -> &'static str {
    match tab {
        Tab::Models => "no models match",
        Tab::Jobs => "no La Forge jobs yet — zc atelier submit SPEC.yaml",
        Tab::Envs => "no running environments — zc env catalog lists what you can start",
        _ => "no Spaces yet",
    }
}

/// The feed's problem or wait, as the whole tab.
fn notice(f: &mut Frame, area: Rect, lines: Vec<Line<'static>>, tab: Tab) {
    f.render_widget(
        Paragraph::new(lines).wrap(Wrap { trim: true }).block(
            Block::bordered()
                .border_style(fg(INK3))
                .title(format!(" {} ", title(tab))),
        ),
        area,
    );
}

pub fn render(f: &mut Frame, area: Rect, app: &App, tab: Tab) {
    let Some(feed) = tab.feed() else { return };
    let doc = match app.feed(feed) {
        FeedState::Loading => {
            let l = Line::from(Span::styled(
                format!(" {} loading from the hub…", spinner(app)),
                fg(INK3),
            ));
            return notice(f, area, vec![l], tab);
        }
        FeedState::Failed(e) => {
            return notice(
                f,
                area,
                vec![
                    Line::from(Span::styled(e.clone(), fg(WARN))),
                    Line::default(),
                    Line::from(Span::styled(
                        "r tries again; `zc login` if the key is the problem",
                        fg(INK3),
                    )),
                ],
                tab,
            )
        }
        FeedState::Ready(d) => d,
    };
    let Some(data) = &doc.table else { return };
    let rows = app.market_rows(tab);
    if rows.is_empty() {
        let hint = match (tab, app.market_filter.is_empty()) {
            (Tab::Models, false) => format!("no model matches “{}”", app.market_filter),
            _ => empty_hint(tab).to_string(),
        };
        return notice(f, area, vec![Line::from(Span::styled(hint, fg(INK3)))], tab);
    }
    let shown: Vec<usize> = (0..data.headers.len())
        .filter(|i| !DETAIL_ONLY.contains(&data.headers[*i].as_str()))
        .collect();
    let cap = |h: &str| match h {
        "MODEL" | "JOB" | "NAME" | "DATASET" => 34,
        "LICENSE" => 12,
        "TASK" => 22,
        _ => 44,
    };
    let widths: Vec<Constraint> = shown
        .iter()
        .map(|&i| Constraint::Length(data.widths()[i].min(cap(&data.headers[i])) as u16))
        .collect();
    let header = Row::new(
        shown
            .iter()
            .map(|&i| Cell::from(data.headers[i].clone()))
            .collect::<Vec<_>>(),
    )
    .style(fg(INK3));
    let body: Vec<Row> = rows
        .iter()
        .map(|r| {
            Row::new(
                shown
                    .iter()
                    .map(|&i| {
                        let cell = crate::market::fmt::clip(
                            r.get(i).map(String::as_str).unwrap_or_default(),
                            cap(&data.headers[i]),
                        );
                        let style = match data.headers[i].as_str() {
                            "STATUS"
                                if matches!(
                                    cell.as_str(),
                                    "running" | "delivered" | "done" | "ready"
                                ) =>
                            {
                                fg(LIVE)
                            }
                            "STATUS"
                                if matches!(cell.as_str(), "failed" | "cancelled" | "stopped") =>
                            {
                                fg(WARN)
                            }
                            "COST" | "PRICE" | "SPENT" => fg(NUM),
                            _ => Default::default(),
                        };
                        Cell::from(cell).style(style)
                    })
                    .collect::<Vec<_>>(),
            )
        })
        .collect();
    let at = app.market_selected(tab).min(rows.len() - 1);
    let filter = match (tab, app.market_filter.is_empty()) {
        (Tab::Models, false) => format!(" · /{}", app.market_filter),
        _ => String::new(),
    };
    let block = Block::bordered().border_style(fg(INK3)).title(format!(
        " {} · {}{filter} ",
        title(tab),
        rows.len()
    ));
    let table = Table::new(body, widths)
        .header(header)
        .block(block)
        .row_highlight_style(selected());
    let (l, r) = match area.width >= SPLIT_W {
        true => {
            let [l, r] =
                Layout::horizontal([Constraint::Percentage(62), Constraint::Percentage(38)])
                    .areas(area);
            (l, Some(r))
        }
        false => (area, None),
    };
    let mut state = TableState::default();
    state.select(Some(at));
    f.render_stateful_widget(table, l, &mut state);
    if let Some(r) = r {
        f.render_widget(detail(data, &rows[at]), r);
    }
}

fn detail(data: &Data, row: &[String]) -> Paragraph<'static> {
    let w = data
        .headers
        .iter()
        .map(|h| h.chars().count())
        .max()
        .unwrap_or(0);
    let lines: Vec<Line> = data
        .headers
        .iter()
        .zip(row)
        .map(|(h, c)| {
            Line::from(vec![
                Span::styled(format!("{:<w$}  ", h.to_lowercase()), fg(INK3)),
                Span::raw(c.clone()),
            ])
        })
        .collect();
    Paragraph::new(lines)
        .wrap(Wrap { trim: false })
        .block(Block::bordered().border_style(fg(INK3)).title(" selected "))
}

/// A feed as lines of the Account tab's usage panel: `label  value`.
pub fn feed_lines(app: &App, id: FeedId, limit: usize) -> Vec<Line<'static>> {
    match app.feed(id) {
        FeedState::Loading => vec![Line::from(Span::styled(
            format!("{} loading…", spinner(app)),
            fg(INK3),
        ))],
        FeedState::Failed(e) => vec![Line::from(Span::styled(
            crate::market::fmt::clip(e, 90),
            fg(WARN),
        ))],
        FeedState::Ready(doc) => {
            let mut out: Vec<Line> = doc
                .kv
                .iter()
                .take(limit)
                .map(|(k, v)| {
                    Line::from(vec![
                        Span::styled(format!("{k:<18}"), fg(INK3)),
                        Span::raw(v.clone()),
                    ])
                })
                .collect();
            if let Some(t) = &doc.table {
                // WHEN, TYPE, JOB, CREDITS: the columns worth a line.
                for r in t.rows.iter().take(limit) {
                    let get = |h: &str| {
                        t.headers
                            .iter()
                            .position(|x| x == h)
                            .and_then(|i| r.get(i))
                            .cloned()
                            .unwrap_or_default()
                    };
                    out.push(Line::from(format!(
                        "{}  {}  {}",
                        get("WHEN"),
                        crate::market::fmt::clip(&get("JOB"), 30),
                        get("CREDITS")
                    )));
                }
                if t.rows.is_empty() {
                    out.push(Line::from(Span::styled("nothing yet", fg(INK3))));
                }
            }
            out
        }
    }
}

/// The Account tab's panel under the device list: spend, quotas, the
/// newest ledger rows, each saying in place when the hub cannot answer.
pub fn usage_panel(f: &mut Frame, area: Rect, app: &App) {
    let [a, b, c] = Layout::horizontal([
        Constraint::Percentage(36),
        Constraint::Percentage(28),
        Constraint::Percentage(36),
    ])
    .areas(area);
    for (r, id, name, n) in [
        (a, FeedId::Usage, " usage ", 4),
        (b, FeedId::Quotas, " request quotas ", 3),
        (c, FeedId::Recent, " recent transactions ", 5),
    ] {
        f.render_widget(
            Paragraph::new(feed_lines(app, id, n))
                .wrap(Wrap { trim: true })
                .block(Block::bordered().border_style(fg(INK3)).title(name)),
            r,
        );
    }
}