use std::path::Path;
use crate::config::option::OptionValue;
use crate::request::request_group::DownloadOptions;
use super::OptionHandler;
use super::parsing::{detect_value_type, parse_kv_arg};
use super::validation::parse_config_line;
pub trait OptionHandlerApply {
fn apply_args(&mut self, args: &[String]);
fn load_config_file(&mut self, path: &Path) -> Result<(), String>;
fn to_download_options(&self) -> DownloadOptions;
}
impl OptionHandlerApply for OptionHandler {
fn apply_args(&mut self, args: &[String]) {
let mut i = 0;
while i < args.len() {
let arg = &args[i];
if !arg.starts_with('-') || arg == "--" {
i += 1;
continue;
}
if let Some((key, value)) = parse_kv_arg(arg) {
if let Some(parsed) = detect_value_type(value.trim()) {
tracing::debug!(key, value = ?parsed, "CLI arg applied");
self.set(key, parsed);
}
i += 1;
continue;
}
if let Some(key) = arg.strip_prefix("--no-") {
self.set(key, OptionValue::Bool(false));
i += 1;
continue;
}
if let Some(key) = arg.strip_prefix("--") {
if i + 1 < args.len() && !args[i + 1].starts_with('-') {
let value = &args[i + 1];
if let Some(parsed) = detect_value_type(value) {
self.set(key, parsed);
}
i += 2;
continue;
} else {
self.set(key, OptionValue::Bool(true));
i += 1;
continue;
}
}
if arg == "-o" && i + 1 < args.len() {
let next = &args[i + 1];
if let Some((key, value)) = next.split_once('=')
&& let Some(parsed) = detect_value_type(value.trim())
{
self.set(key, parsed);
}
i += 2;
continue;
}
i += 1;
}
}
fn load_config_file(&mut self, path: &Path) -> Result<(), String> {
let content = std::fs::read_to_string(path)
.map_err(|e| format!("Failed to read config file '{}': {}", path.display(), e))?;
let path_display = path.display().to_string();
for (line_num, raw_line) in content.lines().enumerate() {
if let Some((key, value_str)) = parse_config_line(raw_line, &path_display, line_num + 1)
{
match detect_value_type(value_str) {
Some(parsed) => {
tracing::debug!(
key,
value = ?parsed,
source = %path_display,
"Config option loaded"
);
self.set(key, parsed);
}
None => {
tracing::warn!(
key,
line = line_num + 1,
source = %path_display,
"Failed to parse config value"
);
}
}
}
}
Ok(())
}
fn to_download_options(&self) -> DownloadOptions {
DownloadOptions::from_option_values(&self.to_map())
}
}