use std::sync::OnceLock;
use serde_json::{Map, Value};
use crate::type_interpreter::CANONICAL_DICTIONARY_JSON;
use crate::layer0::vocabulary_types::{PROVIDER_FIELD_ALIAS_OF, PROVIDER_HANDLE_PREFIX, PROVIDER_PROFILES_SECTION, PROVIDER_PROFILE_TABLE};
fn profiles() -> &'static Map<String, Value> {
static PROFILES: OnceLock<Map<String, Value>> = OnceLock::new();
PROFILES.get_or_init(|| {
let dictionary: Value = serde_json::from_str(CANONICAL_DICTIONARY_JSON).unwrap_or(Value::Null);
dictionary
.get(PROVIDER_PROFILES_SECTION)
.and_then(|section| section.get(PROVIDER_PROFILE_TABLE))
.and_then(Value::as_object)
.cloned()
.unwrap_or_default()
})
}
pub fn provider_profile(name: &str) -> Option<&'static Map<String, Value>> {
let key = name.strip_prefix(PROVIDER_HANDLE_PREFIX).unwrap_or(name);
let profile = profiles().get(key)?.as_object()?;
match profile.get(PROVIDER_FIELD_ALIAS_OF).and_then(Value::as_str) {
Some(alias) => provider_profile(alias),
None => Some(profile),
}
}
pub fn provider_value(name: &str, field: &str) -> Option<&'static Value> {
provider_profile(name)?.get(field)
}
pub fn provider_str(name: &str, field: &str) -> &'static str {
provider_value(name, field)
.and_then(Value::as_str)
.unwrap_or_else(|| panic!("provider profile {name}.{field} is missing from the embedded type dictionary"))
}
pub fn provider_port(name: &str, field: &str) -> u16 {
provider_value(name, field)
.and_then(Value::as_u64)
.and_then(|port| u16::try_from(port).ok())
.unwrap_or_else(|| panic!("provider profile {name}.{field} is missing from the embedded type dictionary"))
}
pub fn provider_ports(name: &str, field: &str) -> Vec<u16> {
provider_value(name, field)
.and_then(Value::as_array)
.map(|ports| ports.iter().filter_map(Value::as_u64).filter_map(|port| u16::try_from(port).ok()).collect())
.unwrap_or_else(|| panic!("provider profile {name}.{field} is missing from the embedded type dictionary"))
}