use std::path::Path;
use std::time::Duration;
use crate::cli::build_core;
use crate::config::{AppConfig, ProfileConfig};
use crate::core::xray::XrayCore;
use crate::engine::benchmark::benchmark_profiles;
use crate::error::{PilotError, Result};
use crate::probe::http::HttpHealthProbe;
pub async fn add_profile(
config_path: &Path,
name: String,
outbound_tag: String,
priority: Option<u32>,
) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
let next_priority =
priority.unwrap_or_else(|| cfg.profiles.iter().map(|p| p.priority).max().unwrap_or(0) + 1);
cfg.add_profile(ProfileConfig {
name: name.clone(),
outbound_tag,
priority: next_priority,
})?;
cfg.save_atomic(config_path).await?;
println!("Added profile '{name}' with priority {next_priority}.");
Ok(())
}
pub async fn import_profiles(
config_path: &Path,
file_path: Option<&Path>,
inline_links: &[String],
auto_benchmark: bool,
) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
let lines = read_import_lines(file_path, inline_links).await?;
let xray = XrayCore::new(
&cfg.core.binary_path,
&cfg.core.config_path,
cfg.core.service_name.clone(),
);
let mut next_priority = cfg.profiles.iter().map(|p| p.priority).max().unwrap_or(0) + 1;
let mut added = 0u32;
for line in lines {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let (name, tag) = if trimmed.starts_with("vless://") {
let parsed = crate::core::xray::vless::parse_vless_uri(trimmed)?;
xray.upsert_outbound(&parsed.outbound_tag, parsed.outbound_json)
.await?;
(parsed.name, parsed.outbound_tag)
} else {
match trimmed.split_once(',') {
Some((n, t)) => (n.trim().to_string(), t.trim().to_string()),
None => (trimmed.to_string(), trimmed.to_string()),
}
};
if cfg
.add_profile(ProfileConfig {
name,
outbound_tag: tag,
priority: next_priority,
})
.is_ok()
{
next_priority += 1;
added += 1;
}
}
cfg.save_atomic(config_path).await?;
println!("Imported {added} new profile(s).");
if auto_benchmark && !cfg.profiles.is_empty() {
println!("Running parallel benchmark to rank profiles and activate the fastest...");
run_benchmark(config_path, false).await?;
}
Ok(())
}
async fn read_import_lines(
file_path: Option<&Path>,
inline_links: &[String],
) -> Result<Vec<String>> {
if let Some(path) = file_path {
let raw = tokio::fs::read_to_string(path).await.map_err(|err| {
PilotError::Config(format!("failed to read {}: {err}", path.display()))
})?;
return Ok(raw.lines().map(ToString::to_string).collect());
}
if !inline_links.is_empty() {
return Ok(inline_links.to_vec());
}
println!("Paste your vless:// links (one per line), then press Enter on an empty line:");
let mut collected = Vec::new();
let stdin = std::io::stdin();
let mut buf = String::new();
while stdin.read_line(&mut buf).is_ok() {
let line = buf.trim().to_string();
buf.clear();
if line.is_empty() {
break;
}
collected.push(line);
}
Ok(collected)
}
pub async fn remove_profile(config_path: &Path, name: &str) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
cfg.remove_profile(name)?;
cfg.save_atomic(config_path).await?;
println!("Removed profile '{name}'.");
Ok(())
}
pub async fn list_profiles(config_path: &Path) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
cfg.profiles.sort_by_key(|p| p.priority);
for p in &cfg.profiles {
println!("[{}] {} (tag: {})", p.priority, p.name, p.outbound_tag);
}
Ok(())
}
pub async fn run_benchmark(config_path: &Path, prune_dead: bool) -> Result<()> {
let mut cfg = AppConfig::load(config_path).await?;
let core = build_core(&cfg)?;
let timeout = Duration::from_secs(cfg.probe.timeout_secs);
let probe = HttpHealthProbe::new(&cfg.core.local_proxy, timeout)?;
let results = benchmark_profiles(
core.as_ref(),
&probe,
|endpoint| Ok(Box::new(HttpHealthProbe::new(endpoint, timeout)?)),
&cfg.profiles,
&cfg.probe.targets,
)
.await?;
for res in &results {
match res.latency {
Some(lat) => println!("OK {:15} {:>4} ms", res.profile.name, lat.as_millis()),
None => println!(
"FAIL {:15} {}",
res.profile.name,
res.error.as_deref().unwrap_or("unknown error")
),
}
}
if prune_dead {
let healthy: Vec<ProfileConfig> = results
.into_iter()
.filter(|r| r.is_healthy())
.enumerate()
.map(|(idx, mut r)| {
r.profile.priority = (idx + 1) as u32;
r.profile
})
.collect();
if healthy.is_empty() {
println!("No healthy profiles found; config.yaml left unchanged.");
} else {
let removed = cfg.profiles.len().saturating_sub(healthy.len());
cfg.profiles = healthy;
cfg.save_atomic(config_path).await?;
println!("Pruned {removed} dead profile(s) and saved sorted healthy list.");
}
} else {
cfg.profiles = results
.into_iter()
.enumerate()
.map(|(idx, mut r)| {
r.profile.priority = (idx + 1) as u32;
r.profile
})
.collect();
cfg.save_atomic(config_path).await?;
}
Ok(())
}