use std::env;
use std::path::PathBuf;

pub const DEFAULT_AXIS_PLATFORM_BASE_URL: &str = "https://nowhub.ipaynow.cn/";
pub const SDK_CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION");

pub fn resolve_platform_base_url() -> String {
    match env::var("AXIS_PAY_PLUGIN_BASE_URL") {
        Ok(value) if !value.trim().is_empty() => value,
        _ => DEFAULT_AXIS_PLATFORM_BASE_URL.to_string(),
    }
}

pub fn axis_plugin_home_dir() -> PathBuf {
    let mut path = home_dir().unwrap_or_else(|| PathBuf::from("."));
    path.push(".axis-pay-plugin");
    path
}

pub fn default_license_cache_path(product_id: &str) -> PathBuf {
    let safe_product_id: String = product_id
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-') {
                ch
            } else {
                '_'
            }
        })
        .collect();
    let mut path = axis_plugin_home_dir();
    path.push(format!("license-{safe_product_id}.json"));
    path
}

pub fn default_device_id_path() -> PathBuf {
    let mut path = axis_plugin_home_dir();
    path.push("device-id");
    path
}

fn home_dir() -> Option<PathBuf> {
    env::var_os("HOME")
        .or_else(|| env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}
