use crate::daemon_port_path;
use anyhow::Result;
use colored::Colorize;
pub async fn handle_ui(port: Option<u16>) -> Result<()> {
let port = port
.or_else(|| {
daemon_port_path()
.and_then(|p| std::fs::read_to_string(p).ok())
.and_then(|s| s.trim().parse::<u16>().ok())
})
.unwrap_or(7878);
let url = format!("http://127.0.0.1:{port}/ui");
let base = format!("http://127.0.0.1:{port}");
crate::commands::daemon_guard::ensure_daemon_running_or_exit(&base).await;
let probe_url = format!("http://127.0.0.1:{port}/health");
let ui_probe_client = trusty_common::server::daemon_http_client()?;
let healthy = ui_probe_client
.get(&probe_url)
.send()
.await
.ok()
.map(|r| r.status().is_success())
.unwrap_or(false);
if !healthy {
eprintln!(
"{} Daemon not reachable at {}. Run {} first.",
"✗".red(),
format!("http://127.0.0.1:{port}").cyan(),
"trusty-search start".cyan(),
);
std::process::exit(1);
}
println!("{} Opening {} …", "◉".green(), url.cyan());
if let Err(e) = open::that(&url) {
eprintln!(
"{} could not launch browser ({e}). Open this URL manually: {}",
"⚠".yellow(),
url
);
}
Ok(())
}