zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `zc setup`: the guided first run (zc#509, plan flow F1 and snapshot S2).
//!
//! The same five steps as the desktop app's first-run screens:
//! welcome → browser sign-in (`zc login`'s device-code flow) → machine check
//! (`zc doctor`'s checks) → share defaults → done. Each step asks one thing,
//! and the defaults are chosen, so pressing Enter all the way through ends
//! with a signed-in machine sharing the conservative default slice.
//!
//! Local state changes go through the agent (ADR ZC-0019 §5): sharing is
//! turned on with `PUT /v1/sharing`, after `zc agent install` when no agent
//! runs yet.

use crate::agent::client::AgentClient;
use crate::setup::{format_check, machine_report, Status};
use std::io::{BufRead, Write};
use std::time::Duration;

const USAGE: &str = "\
Usage: zc setup [--yes] [--no-browser] [--staging] [--no-share]

Set this machine up in five steps: sign in through the browser, check the
machine, choose what to share, and start sharing.

Options:
  -y, --yes        Accept every default without asking.
      --no-browser Print the sign-in URL and code instead of opening a browser.
      --staging    Use the staging hub (same as ZAKURO_ENV=staging).
      --no-share   Sign in and check, but don't start sharing.
  -h, --help       Print this help and exit.
";

#[derive(Debug, Default, PartialEq)]
pub struct Args {
    pub yes: bool,
    pub no_browser: bool,
    pub staging: bool,
    pub no_share: bool,
    pub help: bool,
}

pub fn parse(args: &[String]) -> Result<Args, String> {
    let mut a = Args::default();
    for s in args {
        match s.as_str() {
            "-y" | "--yes" => a.yes = true,
            "--no-browser" => a.no_browser = true,
            "--staging" => a.staging = true,
            "--no-share" => a.no_share = true,
            "-h" | "--help" => a.help = true,
            other => return Err(format!("unknown argument '{other}'")),
        }
    }
    Ok(a)
}

/// The step header: `[2/5] Sign in`.
pub fn step(n: u8, title: &str) -> String {
    format!("\n  [{n}/5] {title}")
}

fn ask_yes(question: &str, default_yes: bool, auto: bool) -> bool {
    if auto {
        return default_yes;
    }
    print!(
        "  {question} {} ",
        if default_yes { "[Y/n]" } else { "[y/N]" }
    );
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    if std::io::stdin().lock().read_line(&mut line).is_err() {
        return default_yes;
    }
    match line.trim().to_ascii_lowercase().as_str() {
        "" => default_yes,
        "y" | "yes" => true,
        _ => false,
    }
}

fn signed_in() -> bool {
    std::env::var("ZAKURO_API_KEY").is_ok_and(|k| !k.trim().is_empty())
}

/// What `zc setup` proposes to lend, before the sharing policy (zc#514) and
/// the CPU/RAM budget (zc#513) exist: the agent's worker cap, which is half
/// the CPUs, at least one.
pub fn share_defaults(cpus: usize, max_workers_env: Option<&str>) -> String {
    let workers = crate::agent::config::parse_max_workers(max_workers_env, cpus);
    format!(
        "up to {workers} worker{} (half of {cpus} CPUs), at your account's default price",
        if workers == 1 { "" } else { "s" }
    )
}

pub fn run(args: &[String]) -> i32 {
    let a = match parse(args) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("{e}\n\n{USAGE}");
            return 2;
        }
    };
    if a.help {
        print!("{USAGE}");
        return 0;
    }
    if a.staging && std::env::var(crate::profile::ENV_VAR).is_err() {
        std::env::set_var(crate::profile::ENV_VAR, "staging");
    }
    crate::credentials::load_into_env();

    // 1. Welcome.
    println!(
        "\n  Zakuro setup · {} · {}",
        std::env::consts::OS,
        std::env::consts::ARCH
    );
    println!("{}", step(1, "Welcome"));
    println!("  Zakuro runs other people's jobs on this machine and pays you for the time.");
    println!("  You decide how much to lend, and you can pause any time (zc unshare).");

    // 2. Sign in.
    println!("{}", step(2, "Sign in with your browser"));
    if signed_in() {
        println!(
            "  ✓ Already signed in ({})",
            crate::credentials::default_api_url()
        );
    } else {
        let code = crate::init::run_with(crate::init::LoginArgs {
            staging: a.staging,
            no_connect: true,
            no_browser: a.no_browser,
            ..Default::default()
        });
        if code != 0 {
            eprintln!("  ✗ Not signed in. Run `zc setup` again when you're ready.");
            return code;
        }
        crate::credentials::load_into_env();
    }

    // 3. Machine check.
    println!("{}", step(3, "Checking this machine"));
    let report = machine_report(true);
    for c in &report.checks {
        println!("{}", format_check(c));
    }
    if !report.ok() {
        let failed: Vec<&str> = report
            .checks
            .iter()
            .filter(|c| c.status == Status::Fail)
            .map(|c| c.label.as_str())
            .collect();
        eprintln!(
            "\n  ✗ Fix these first, then run `zc setup` again: {}",
            failed.join(", ")
        );
        return 1;
    }

    // 4. Share defaults.
    println!("{}", step(4, "Your share"));
    let cpus = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1);
    println!(
        "  Default: {}.",
        share_defaults(
            cpus,
            std::env::var("ZAKURO_AGENT_MAX_WORKERS").ok().as_deref()
        )
    );
    println!("  Change it later with `zc price`, the app's Budget & price, or the hub.");
    println!("  The public squad and CPU/memory limits arrive with zc#514 and zc#513.");
    let share = !a.no_share && ask_yes("Start sharing this machine now?", true, a.yes);

    if share {
        if let Err(e) = start_sharing() {
            eprintln!("  ✗ {e}");
            eprintln!("  Retry with `zc agent install` then `zc share`.");
            return 1;
        }
        println!("  ✓ Sharing, through the zc agent");
    } else {
        println!("  Not sharing yet. Start any time with `zc share`.");
    }

    // 5. Done.
    println!("{}", step(5, "Done"));
    if share {
        println!("  You're contributing.");
        println!("  See it live: zc jobs --live · or open Zakuro");
    } else {
        println!("  Signed in and checked. `zc share` starts sharing.");
    }
    0
}

/// `PUT /v1/sharing {"on": true}` on the running agent, installing it first
/// when none answers.
fn start_sharing() -> Result<(), String> {
    let client = match AgentClient::running() {
        Some(c) => c,
        None => {
            println!("  Installing the zc agent (it keeps sharing running in the background)…");
            if crate::agent::cli::install() != 0 {
                return Err("zc agent install failed".into());
            }
            let mut found = None;
            for _ in 0..20 {
                if let Some(c) = AgentClient::running() {
                    found = Some(c);
                    break;
                }
                std::thread::sleep(Duration::from_millis(500));
            }
            found.ok_or("the agent was installed but isn't answering yet")?
        }
    };
    client
        .put(
            "/v1/sharing",
            serde_json::json!({ "on": true }),
            Duration::from_secs(60),
        )
        .map(|_| ())
}

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

    fn args(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn flags_parse() {
        let a = parse(&args(&["--yes", "--no-browser", "--staging", "--no-share"])).unwrap();
        assert!(a.yes && a.no_browser && a.staging && a.no_share);
        assert!(parse(&args(&["--nope"])).is_err());
        assert!(parse(&args(&["-h"])).unwrap().help);
    }

    #[test]
    fn the_default_share_is_half_the_cpus() {
        assert_eq!(
            share_defaults(12, None),
            "up to 6 workers (half of 12 CPUs), at your account's default price"
        );
        assert!(share_defaults(1, None).starts_with("up to 1 worker "));
        assert!(share_defaults(12, Some("2")).starts_with("up to 2 workers"));
        assert_eq!(
            step(3, "Checking this machine"),
            "\n  [3/5] Checking this machine"
        );
    }
}