curd-editor 0.27.1

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! Who is signed in to an assistant, as its own program tells it.

use super::*;

/// What a command that says who is signed in printed, in one line. The
/// `claude` command answers in JSON; anything else is shown as it is.
pub fn account(printed: &str) -> String {
    let printed = printed.trim();
    match serde_json::from_str::<Value>(printed) {
        Ok(status) if status["loggedIn"].as_bool() == Some(false) => {
            "Not signed in. Type /login to sign in.".into()
        }
        Ok(status) if status["loggedIn"].as_bool() == Some(true) => {
            let who = status["email"].as_str().unwrap_or("an account");
            match status["subscriptionType"].as_str() {
                Some(plan) => format!("Signed in as {who}, on the {plan} plan"),
                None => format!("Signed in as {who}"),
            }
        }
        _ if printed.is_empty() => "It did not say".into(),
        _ => crate::runner::clean(&printed.lines().collect::<Vec<_>>().join("  ")),
    }
}

/// What is known about the account an assistant uses. It is the first
/// thing its panel shows, before anything is asked.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Account {
    /// Not looked at yet, or there is no way to tell.
    #[default]
    Unknown,
    /// Its program is not on this machine: how to get it.
    Missing(String),
    SignedOut,
    /// Signed in: who as, if it said.
    SignedIn(String),
}

/// What an assistant's own command for saying who is signed in means:
/// `printed` is what it printed, `succeeded` whether it ended well.
pub fn account_state(printed: &str, succeeded: bool) -> Account {
    let said = printed.to_lowercase();
    let signed_out = ["not logged in", "not signed in", "not authenticated", "logged out", "\"loggedin\": false", "\"loggedin\":false"];
    if !succeeded || signed_out.iter().any(|words| said.contains(words)) {
        Account::SignedOut
    } else {
        Account::SignedIn(account(printed))
    }
}