//! # `pinchar` library crate
//!
//! If you are reading this, you are reading the documentation for the `pinchar` library crate. For the cli, kindly refer to the README file.

#![deny(missing_docs)]
#![warn(clippy::all, clippy::nursery, clippy::pedantic, clippy::cargo)]

use pinyin::ToPinyin;
use std::{collections::HashMap, sync::LazyLock};

/// Lazy-initialized static `HashMap` mapping pinyin to characters.
static PINYIN_MAP: LazyLock<HashMap<String, Vec<char>>> = LazyLock::new(|| {
    let mut map: HashMap<String, Vec<char>> = HashMap::new();

    // Range of common Chinese characters (CJK Unified Ideographs)
    let start = '\u{4E00}';
    let end = '\u{9FFF}';

    for ch in start..=end {
        if let Some(py) = ch.to_pinyin() {
            let pinyin_str = py.plain().to_lowercase();
            map.entry(pinyin_str).or_default().push(ch);
        }
    }

    map
});

/// Lists Chinese characters that correspond to the given pinyin input.
///
/// This function searches through common Chinese characters (Unicode range U+4E00 to U+9FFF)
/// and returns those whose pinyin matches the input string (case-insensitive, tone-insensitive).
///
/// # Arguments
///
/// * `pinyin` - The pinyin string to search for (e.g., "he", "ni", "hao")
///
/// # Returns
///
/// A static slice of characters that match the given pinyin.
///
/// # Examples
///
/// ```
/// use pinchar::characters_from_pinyin;
///
/// let chars = characters_from_pinyin("he");
/// assert!(chars.contains(&'和'));
/// assert!(chars.contains(&'河'));
/// ```
pub fn characters_from_pinyin(pinyin: &str) -> &'static [char] {
    let normalized_pinyin = pinyin.to_lowercase();

    // Use the pre-built map for O(1) lookup instead of iterating through all characters
    PINYIN_MAP
        .get(&normalized_pinyin)
        .map_or(&[], |v| v.as_slice())
}
