use ferrous_opencc::{config::BuiltinConfig, OpenCC};
use once_cell::sync::Lazy;

static OPENCC_S2T: Lazy<OpenCC> = Lazy::new(|| {
    OpenCC::from_config(BuiltinConfig::S2t)
        .expect("Failed to initialize OpenCC Simplified to Traditional converter")
});

static OPENCC_T2S: Lazy<OpenCC> = Lazy::new(|| {
    OpenCC::from_config(BuiltinConfig::T2s)
        .expect("Failed to initialize OpenCC Traditional to Simplified converter")
});

/// Convert Simplified Chinese text to Traditional Chinese
pub fn simplified_to_traditional(text: &str) -> String {
    OPENCC_S2T.convert(text)
}

/// Convert Traditional Chinese text to Simplified Chinese
pub fn traditional_to_simplified(text: &str) -> String {
    OPENCC_T2S.convert(text)
}

/// Normalize Chinese query for search:
/// 1. Convert Simplified Chinese to Traditional Chinese (assuming database stores Traditional)
/// 2. Return converted text
pub fn normalize_chinese_query(text: &str) -> String {
    simplified_to_traditional(text)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simplified_to_traditional() {
        // Example: Simplified "计算机" -> Traditional "計算機"
        let simplified = "计算机";
        let traditional = simplified_to_traditional(simplified);
        // The conversion might produce "計算機" (depending on dictionary)
        // We'll just verify it's not empty and different from input
        assert!(!traditional.is_empty());
        assert_ne!(traditional, simplified);

        // Traditional input should remain unchanged (or nearly unchanged)
        let traditional_input = "計算機";
        let converted = simplified_to_traditional(traditional_input);
        assert_eq!(converted, traditional_input);
    }

    #[test]
    fn test_traditional_to_simplified() {
        let traditional = "計算機";
        let simplified = traditional_to_simplified(traditional);
        assert!(!simplified.is_empty());
        assert_ne!(simplified, traditional);
    }

    #[test]
    fn test_normalize_chinese_query() {
        let simplified = "计算机";
        let normalized = normalize_chinese_query(simplified);
        // Should be Traditional
        assert_ne!(normalized, simplified);

        let traditional = "計算機";
        let normalized2 = normalize_chinese_query(traditional);
        // Should remain Traditional
        assert_eq!(normalized2, traditional);
    }
}
