use std::ffi::OsString;
use std::path::{Path, PathBuf};
use super::super::adapter::Agent;
use super::super::text::say;
use super::{Launch, cursor, muse, pi, store, vibe};
type Env<'a> = &'a dyn Fn(&str) -> Option<OsString>;
pub(super) fn presets(
agent: Agent,
selection: &[String],
directory: &Path,
) -> Result<Launch, String> {
if agent == Agent::Cursor {
return Err(say("cursor_macos_only", &[]));
}
if !matches!(agent, Agent::Pi | Agent::Vibe | Agent::Muse) {
return Ok(Launch::Presets { unset: Vec::new() });
}
let stores = store::check(selection, directory)?;
if stores.login {
return Err(say("pi_login_readable", &[]));
}
Ok(Launch::Presets {
unset: stores.unset,
})
}
pub fn ready(
agent: Agent,
turn: (&str, bool),
directory: &Path,
state: (&Path, Option<&Path>, Option<&Path>),
) -> Result<Option<super::super::pi::Paths>, String> {
let home = super::super::adapter::home().and_then(|home| home.canonicalize().ok());
let home = home.ok_or_else(|| say("sandbox_home", &[]));
let var = |name: &str| std::env::var_os(name);
let persist = super::cursor_run::root();
ready_in(agent, turn, directory, state, (home, &var, &persist))
}
pub fn ready_in(
agent: Agent,
(session, resume): (&str, bool),
directory: &Path,
(private, child_home, session_dir): (&Path, Option<&Path>, Option<&Path>),
(home, var, persist): (Result<PathBuf, String>, Env, &Path),
) -> Result<Option<super::super::pi::Paths>, String> {
if let Some(kind) = super::super::home::kind(agent) {
let child_home = vibe::validate(kind, child_home, private)?;
super::super::home::renew(agent, &child_home, resume.then_some(session))?;
if agent == Agent::Muse {
let dir = session_dir.ok_or_else(|| say("muse_session_dir", &[("directory", "")]))?;
muse::validate(&home?, var, dir, session)?;
}
return Ok(None);
}
if !matches!(agent, Agent::Pi | Agent::Cursor) {
return Ok(None);
}
let home = home?;
match agent {
Agent::Pi => pi::prepare(&home, var, session, resume, directory).map(Some),
_ if resume => {
super::cursor_run::ready(persist)?;
cursor::chat_ready(&home, var, directory, session).map(|()| None)
}
_ => Ok(None),
}
}