use dictx_core::Query;
use dictx_index::is_cjk;

pub fn parse_lookup_query(word: &str) -> Query {
    Query::Exact {
        word: word.trim().to_lowercase(),
    }
}

pub fn parse_search_query(input: &str, fuzzy_distance: u8) -> Query {
    let input = input.trim();
    if let Some(rest) = input.strip_prefix('~') {
        return Query::Fuzzy {
            word: rest.trim().to_lowercase(),
            distance: fuzzy_distance,
        };
    }
    if input.contains('*') || input.contains('?') {
        return Query::Wildcard {
            pattern: input.to_lowercase(),
        };
    }
    if input.chars().any(is_cjk) {
        return Query::Chinese {
            text: input.to_string(),
        };
    }
    Query::FullText {
        text: input.to_string(),
    }
}

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

    #[test]
    fn detects_fuzzy_prefix() {
        assert!(matches!(
            parse_search_query("~appple", 2),
            Query::Fuzzy { .. }
        ));
    }

    #[test]
    fn detects_chinese() {
        assert!(matches!(
            parse_search_query("苹果", 2),
            Query::Chinese { .. }
        ));
    }
}
