use super::super::super::*;

pub(in crate::inspect::smp) fn runtime_candidate_availability_name(label: &str) -> String {
    label
        .strip_suffix(" Availability")
        .unwrap_or(label)
        .to_string()
}

pub(in crate::inspect::smp) fn runtime_world_flag_key(
    descriptor_metadata: RealGroupedEffectDescriptorMetadata,
) -> Option<String> {
    descriptor_metadata
        .runtime_key
        .map(str::to_string)
        .or_else(|| {
            (descriptor_metadata.parameter_family == "world_flag_toggle")
                .then(|| runtime_world_flag_key_from_label(descriptor_metadata.label))
        })
}

pub(crate) fn runtime_world_flag_key_from_label(label: &str) -> String {
    normalize_runtime_world_key(label)
}

pub(in crate::inspect::smp) fn runtime_world_scalar_key(
    descriptor_metadata: RealGroupedEffectDescriptorMetadata,
) -> Option<String> {
    descriptor_metadata
        .runtime_key
        .map(str::to_string)
        .or_else(|| {
            (descriptor_metadata.parameter_family == "world_scalar_override")
                .then(|| normalize_runtime_world_key(descriptor_metadata.label))
        })
}

pub(crate) fn runtime_world_scalar_key_from_label(label: &str) -> String {
    normalize_runtime_world_key(label)
}

pub(in crate::inspect::smp) fn normalize_runtime_world_key(label: &str) -> String {
    let mut key = String::with_capacity(label.len() + 6);
    key.push_str("world.");
    let mut last_was_underscore = false;
    for ch in label.chars() {
        if ch.is_ascii_alphanumeric() {
            key.push(ch.to_ascii_lowercase());
            last_was_underscore = false;
        } else if !last_was_underscore {
            key.push('_');
            last_was_underscore = true;
        }
    }
    while key.ends_with('_') {
        key.pop();
    }
    key
}

pub(in crate::inspect::smp) fn real_grouped_company_governance_metric(
    descriptor_metadata: RealGroupedEffectDescriptorMetadata,
) -> Option<RuntimeCompanyMetric> {
    match descriptor_metadata.label {
        "Credit Rating" => Some(RuntimeCompanyMetric::CreditRating),
        "Prime Rate" => Some(RuntimeCompanyMetric::PrimeRate),
        "Book Value Per Share" => Some(RuntimeCompanyMetric::BookValuePerShare),
        "Investor Confidence" => Some(RuntimeCompanyMetric::InvestorConfidence),
        "Management Attitude" => Some(RuntimeCompanyMetric::ManagementAttitude),
        _ => None,
    }
}
