use std::collections::{BTreeMap, BTreeSet};
use std::convert::Infallible;
use std::fmt;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::ops::{ControlFlow, Deref};
use std::str::FromStr;

use deserr::{DeserializeError, Deserr, ErrorKind, MergeWithError, ValuePointerRef};
use fst::IntoStreamer;
use milli::disabled_typos_terms::DisabledTyposTerms;
use milli::index::PrefixSearch;
use milli::proximity::ProximityPrecision;
pub use milli::update::ChatSettings;
use milli::update::Setting;
use milli::vector::db::IndexEmbeddingConfig;
use milli::{
    Criterion, CriterionError, FilterableAttributesRule, ForeignKey, Index,
    DEFAULT_VALUES_PER_FACET,
};
use serde::{Deserialize, Serialize, Serializer};
use utoipa::ToSchema;

use crate::deserr::DeserrJsonError;
use crate::error::deserr_codes::*;
use crate::facet_values_sort::FacetValuesSort;
use crate::locales::LocalizedAttributesRuleView;

/// The maximum number of results that the engine
/// will be able to return in one search call.
pub const DEFAULT_PAGINATION_MAX_TOTAL_HITS: usize = 1000;

fn serialize_with_wildcard<S>(
    field: &Setting<Vec<String>>,
    s: S,
) -> std::result::Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let wildcard = vec!["*".to_string()];
    match field {
        Setting::Set(value) => Some(value),
        Setting::Reset => Some(&wildcard),
        Setting::NotSet => None,
    }
    .serialize(s)
}

#[derive(Clone, Default, Debug, Serialize, PartialEq, Eq, ToSchema)]
pub struct Checked;

#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct Unchecked;

impl<E> Deserr<E> for Unchecked
where
    E: DeserializeError,
{
    fn deserialize_from_value<V: deserr::IntoValue>(
        _value: deserr::Value<V>,
        _location: deserr::ValuePointerRef,
    ) -> Result<Self, E> {
        unreachable!()
    }
}

fn validate_min_word_size_for_typo_setting<E: DeserializeError>(
    s: MinWordSizeTyposSetting,
    location: ValuePointerRef,
) -> Result<MinWordSizeTyposSetting, E> {
    if let (Setting::Set(one), Setting::Set(two)) = (s.one_typo, s.two_typos) {
        if one > two {
            return Err(deserr::take_cf_content(E::error::<Infallible>(None, ErrorKind::Unexpected { msg: format!("`minWordSizeForTypos` setting is invalid. `oneTypo` and `twoTypos` fields should be between `0` and `255`, and `twoTypos` should be greater or equals to `oneTypo` but found `oneTypo: {one}` and twoTypos: {two}`.") }, location)));
        }
    }
    Ok(s)
}

/// Minimum word length required before typos are allowed.
///
/// This helps prevent matching very short words with typos, which can lead to irrelevant results.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Deserr, ToSchema)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
#[deserr(deny_unknown_fields, rename_all = camelCase, validate = validate_min_word_size_for_typo_setting -> DeserrJsonError<InvalidSettingsTypoTolerance>)]
pub struct MinWordSizeTyposSetting {
    /// Minimum word length to accept one typo. Shorter words must match exactly. For example, if set to 5, "apple" can have one typo but "app" cannot.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<u8>, default = 5, example = json!(5))]
    pub one_typo: Setting<u8>,
    /// Minimum word length to accept two typos. Must be greater than or equal to `oneTypo`. For example, if set to 9, "computing" can have two typos.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<u8>, default = 9, example = json!(9))]
    pub two_typos: Setting<u8>,
}

/// Typo tolerance: how spelling mistakes in queries are handled.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Deserr, ToSchema)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
#[deserr(deny_unknown_fields, rename_all = camelCase, where_predicate = __Deserr_E: deserr::MergeWithError<DeserrJsonError<InvalidSettingsTypoTolerance>>)]
pub struct TypoSettings {
    /// When true, typo tolerance is enabled. When false, only exact matches are returned.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<bool>, default = true, example = json!(true))]
    pub enabled: Setting<bool>,
    /// Minimum word length before typos are allowed. Contains `oneTypo` (min length for 1 typo) and `twoTypos` (min length for 2 typos). Example: `{ "oneTypo": 5, "twoTypos": 9 }`.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsTypoTolerance>)]
    #[schema(value_type = Option<MinWordSizeTyposSetting>, default = json!({ "oneTypo": 5, "twoTypos": 9 }), example = json!({ "oneTypo": 5, "twoTypos": 9 }))]
    pub min_word_size_for_typos: Setting<MinWordSizeTyposSetting>,
    /// Words for which typo tolerance is disabled. Use for brand names or terms that must match exactly.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<BTreeSet<String>>, default = json!([]), example = json!(["iPhone", "phone"]))]
    pub disable_on_words: Setting<BTreeSet<String>>,
    /// Attributes for which typo tolerance is disabled. Those attributes only return exact matches. Useful for fields like product codes or IDs.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<BTreeSet<String>>, default = json!([]), example = json!(["uuid", "url"]))]
    pub disable_on_attributes: Setting<BTreeSet<String>>,
    /// When true, typo tolerance is disabled on numeric tokens. For example, 123 will not match 132.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<bool>, default = false, example = json!(false))]
    pub disable_on_numbers: Setting<bool>,
}

/// Faceting: maximum number of facet values and how they are sorted.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Deserr, ToSchema)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
#[deserr(rename_all = camelCase, deny_unknown_fields)]
pub struct FacetingSettings {
    /// Maximum number of facet values returned per facet. Values are sorted in ascending lexicographical order.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<usize>, default = 100, example = json!(100))]
    pub max_values_per_facet: Setting<usize>,
    /// Sort order per facet: by descending count (`count`) or ascending alphanumeric (`alpha`). Key `*` applies to all facets.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<BTreeMap<String, FacetValuesSort>>, default = json!({ "*": "alpha" }), example = json!({ "*": FacetValuesSort::Alpha }))]
    pub sort_facet_values_by: Setting<BTreeMap<String, FacetValuesSort>>,
}

/// Pagination: cap on how many results a search can return.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Deserr, ToSchema)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
#[deserr(rename_all = camelCase, deny_unknown_fields)]
pub struct PaginationSettings {
    /// Maximum number of search results Meilisearch can return. Limit and offset cannot go beyond this value.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default)]
    #[schema(value_type = Option<usize>, default = 1000, example = json!(1000))]
    pub max_total_hits: Setting<NonZeroUsize>,
}

impl MergeWithError<milli::CriterionError> for DeserrJsonError<InvalidSettingsRankingRules> {
    fn merge(
        _self_: Option<Self>,
        other: milli::CriterionError,
        merge_location: ValuePointerRef,
    ) -> ControlFlow<Self, Self> {
        Self::error::<Infallible>(
            None,
            ErrorKind::Unexpected { msg: other.to_string() },
            merge_location,
        )
    }
}

#[derive(Default, Serialize, Deserialize, PartialEq, Eq, Clone, ToSchema)]
#[repr(transparent)]
#[serde(transparent)]
/// Configuration for one [embedder](https://www.meilisearch.com/docs/learn/ai_powered_search/getting_started_with_ai_search) used for semantic and hybrid search.
///
/// Set `source` (`openAi`, `huggingFace`, `ollama`, `rest`, `userProvided`), then the options that apply: `model`, `apiKey`, `documentTemplate`, `dimensions`, `url`, etc.
pub struct SettingEmbeddingSettings {
    #[schema(inline, value_type = Option<crate::milli::vector::settings::EmbeddingSettings>)]
    pub inner: Setting<crate::milli::vector::settings::EmbeddingSettings>,
}

impl fmt::Debug for SettingEmbeddingSettings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl<E: DeserializeError> Deserr<E> for SettingEmbeddingSettings {
    fn deserialize_from_value<V: deserr::IntoValue>(
        value: deserr::Value<V>,
        location: ValuePointerRef,
    ) -> Result<Self, E> {
        Setting::<crate::milli::vector::settings::EmbeddingSettings>::deserialize_from_value(
            value, location,
        )
        .map(|inner| Self { inner })
    }
}

/// Index settings: every option you can configure for search and index behavior.
///
/// Used as the request body for PATCH settings. Only the fields you send are updated; pass `null` to reset a setting to its default.
///
/// See also: [Configuring index settings on the Cloud](https://www.meilisearch.com/docs/learn/configuration/configuring_index_settings).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Deserr, ToSchema)]
#[serde(
    // We don't deny unknown fields for backward compatibility with
    // settings that were previously written in the task queue.
    // Note that we use serde to store the settings in the task
    // queue and changing this parameter doesn't impact the HTTP
    // route as we are using deser there.
    //
    // deny_unknown_fields,
    rename_all = "camelCase",
    bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'static>")
)]
#[deserr(error = DeserrJsonError, rename_all = camelCase, deny_unknown_fields)]
#[schema(rename_all = "camelCase")]
pub struct Settings<T> {
    /// Fields returned in search results. Affects only search endpoints, not get-document endpoints. See [displayed and searchable attributes](https://www.meilisearch.com/docs/learn/relevancy/displayed_searchable_attributes).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsDisplayedAttributes>)]
    #[schema(value_type = Option<Vec<String>>, default = json!(["*"]), example = json!(["id", "title", "description", "url"]))]
    pub displayed_attributes: WildcardSetting,

    /// Fields searched for query words, in order of importance. Defines [attribute ranking order](https://www.meilisearch.com/docs/learn/relevancy/attribute_ranking_order). See [displayed and searchable attributes](https://www.meilisearch.com/docs/learn/relevancy/displayed_searchable_attributes).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsSearchableAttributes>)]
    #[schema(value_type = Option<Vec<String>>, default = json!(["*"]), example = json!(["title", "description"]))]
    pub searchable_attributes: WildcardSetting,

    /// Attributes that can be used as [filters](https://www.meilisearch.com/docs/learn/filtering_and_sorting/filter_search_results) and [facets](https://www.meilisearch.com/docs/learn/filtering_and_sorting/search_with_facet_filters). Strings or objects with `attributePatterns` and `features`.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsFilterableAttributes>)]
    #[schema(value_type = Option<Vec<FilterableAttributesRule>>, default = json!([]), example = json!(["release_date", "genre"]))]
    pub filterable_attributes: Setting<Vec<FilterableAttributesRule>>,

    /// Attributes that can be used to [sort search results](https://www.meilisearch.com/docs/learn/filtering_and_sorting/sort_search_results).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsSortableAttributes>)]
    #[schema(value_type = Option<Vec<String>>, default = json!([]), example = json!(["release_date"]))]
    pub sortable_attributes: Setting<BTreeSet<String>>,

    /// Foreign keys to use for cross-index filtering search.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsForeignKeys>)]
    #[schema(value_type = Option<Vec<ForeignKey>>, example = json!([{"foreignIndexUid": "products", "fieldName": "productId"}]))]
    pub foreign_keys: Setting<Vec<ForeignKey>>,

    /// [Ranking rules](https://www.meilisearch.com/docs/learn/relevancy/ranking_rules) in order of importance. Built-in rules and custom sort rules (`attribute:asc` or `attribute:desc`).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsRankingRules>)]
    #[schema(value_type = Option<Vec<String>>, default = json!(["words", "typo", "proximity", "attributeRank", "sort", "wordPosition", "exactness"]), example = json!(["words", "typo", "proximity", "attributeRank", "sort", "wordPosition", "exactness"]))]
    pub ranking_rules: Setting<Vec<RankingRuleView>>,

    /// Words ignored when present in search queries.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsStopWords>)]
    #[schema(value_type = Option<Vec<String>>, default = json!([]), example = json!(["the", "a"]))]
    pub stop_words: Setting<BTreeSet<String>>,

    /// Characters that are not treated as word separators. Removed from the default separator set.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsNonSeparatorTokens>)]
    #[schema(value_type = Option<Vec<String>>, default = json!([]), example = json!(["@", "#"]))]
    pub non_separator_tokens: Setting<BTreeSet<String>>,

    /// Characters that delimit words. Added on top of the default separators.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsSeparatorTokens>)]
    #[schema(value_type = Option<Vec<String>>, default = json!([]), example = json!(["|"]))]
    pub separator_tokens: Setting<BTreeSet<String>>,

    /// Strings Meilisearch parses as a single term. Useful for names or domain terms.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsDictionary>)]
    #[schema(value_type = Option<Vec<String>>, default = json!([]), example = json!(["J. R. R."]))]
    pub dictionary: Setting<BTreeSet<String>>,

    /// Pairs of words or phrases treated as equivalent for search. Key maps to an array of [synonyms](https://www.meilisearch.com/docs/learn/relevancy/synonyms).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsSynonyms>)]
    #[schema(value_type = Option<BTreeMap<String, Vec<String>>>, default = json!({}), example = json!({ "phone": ["iPhone"] }))]
    pub synonyms: Setting<BTreeMap<String, Vec<String>>>,

    /// Field whose value must be unique in the returned documents. One document per distinct value. See [distinct attribute](https://www.meilisearch.com/docs/learn/relevancy/distinct_attribute).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsDistinctAttribute>)]
    #[schema(value_type = Option<String>, example = json!("sku"))]
    pub distinct_attribute: Setting<String>,

    /// Precision for the proximity ranking rule and phrase search: `byWord` (exact distance) or `byAttribute` (same attribute).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsProximityPrecision>)]
    #[schema(value_type = Option<String>, default = json!("byWord"), example = json!(ProximityPrecisionView::ByWord))]
    pub proximity_precision: Setting<ProximityPrecisionView>,

    /// [Typo tolerance](https://www.meilisearch.com/docs/learn/relevancy/typo_tolerance_settings): enable/disable, minimum word length for typos, and where to disable it.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsTypoTolerance>)]
    #[schema(value_type = Option<TypoSettings>, default = json!({ "enabled": true, "minWordSizeForTypos": { "oneTypo": 5, "twoTypos": 9 }, "disableOnWords": [], "disableOnAttributes": [], "disableOnNumbers": false }), example = json!({ "enabled": true, "disableOnAttributes": ["title"] }))]
    pub typo_tolerance: Setting<TypoSettings>,

    /// Related to [faceting](https://www.meilisearch.com/docs/learn/filtering_and_sorting/search_with_facet_filters): max facet values per facet and how facet values are sorted.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsFaceting>)]
    #[schema(value_type = Option<FacetingSettings>, default = json!({ "maxValuesPerFacet": 100, "sortFacetValuesBy": { "*": "alpha" } }), example = json!({ "maxValuesPerFacet": 100, "sortFacetValuesBy": { "genre": "count" } }))]
    pub faceting: Setting<FacetingSettings>,

    /// Related to [pagination](https://www.meilisearch.com/docs/guides/front_end/pagination): maximum number of results a search can return.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsPagination>)]
    #[schema(value_type = Option<PaginationSettings>, default = json!({ "maxTotalHits": 1000 }), example = json!({ "maxTotalHits": 1000 }))]
    pub pagination: Setting<PaginationSettings>,

    /// [Embedders](https://www.meilisearch.com/docs/learn/ai_powered_search/getting_started_with_ai_search) used for semantic and [hybrid search](https://www.meilisearch.com/docs/learn/ai_powered_search/getting_started_with_ai_search). Map of embedder name to config (`source`, `model`, `documentTemplate`, etc.).
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsEmbedders>)]
    #[schema(value_type = Option<BTreeMap<String, crate::milli::vector::settings::EmbeddingSettings>>, default = json!({}), example = json!({ "default": { "source": "openAi", "model": "text-embedding-3-small", "documentTemplate": "{{doc.title}}: {{doc.overview}}" } }), nullable = true)]
    pub embedders: Setting<BTreeMap<String, SettingEmbeddingSettings>>,

    /// Maximum duration of a search in milliseconds. If reached, the search stops and returns results computed so far. When null, 1500 ms is used.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsSearchCutoffMs>)]
    #[schema(value_type = Option<u64>, example = json!(1500))]
    pub search_cutoff_ms: Setting<u64>,

    /// Locales and attribute patterns for [language-specific tokenization](https://www.meilisearch.com/docs/learn/resources/language). Affects searchable, filterable, and sortable attributes.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsLocalizedAttributes>)]
    #[schema(value_type = Option<Vec<LocalizedAttributesRuleView>>, default = json!([]), example = json!([{"locales": ["jpn"], "attributePatterns": ["*_ja"]}]))]
    pub localized_attributes: Setting<Vec<LocalizedAttributesRuleView>>,

    /// When true, [facet search](https://www.meilisearch.com/docs/learn/filtering_and_sorting/search_with_facet_filters) is enabled. When false, the facet-search endpoint is disabled.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsFacetSearch>)]
    #[schema(value_type = Option<bool>, default = true, example = json!(true))]
    pub facet_search: Setting<bool>,

    /// When to compute prefix matches: `indexingTime` or `disabled`. `disabled` speeds up indexing but reduces relevancy.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsPrefixSearch>)]
    #[schema(value_type = Option<PrefixSearchSettings>, default = json!("indexingTime"), example = json!(PrefixSearchSettings::IndexingTime))]
    pub prefix_search: Setting<PrefixSearchSettings>,

    /// [Chat (conversation)](https://www.meilisearch.com/docs/learn/chat/getting_started_with_chat) settings: index description, document template, and search parameters used when the LLM queries this index.
    #[serde(default, skip_serializing_if = "Setting::is_not_set")]
    #[deserr(default, error = DeserrJsonError<InvalidSettingsIndexChat>)]
    #[schema(value_type = Option<ChatSettings>, default = json!({}), example = json!({ "description": "A comprehensive movie database", "documentTemplateMaxBytes": 400, "searchParameters": { "limit": 20 } }))]
    pub chat: Setting<ChatSettings>,

    #[serde(skip)]
    #[deserr(skip)]
    pub _kind: PhantomData<T>,
}

impl<T> Settings<T> {
    pub fn hide_secrets(&mut self) {
        let Setting::Set(embedders) = &mut self.embedders else {
            return;
        };

        for mut embedder in embedders.values_mut() {
            let SettingEmbeddingSettings { inner: Setting::Set(embedder) } = &mut embedder else {
                continue;
            };

            let Setting::Set(api_key) = &mut embedder.api_key else {
                continue;
            };

            hide_secret(api_key, 0);
        }
    }
}

/// Redact a secret string, starting from the `secret_offset`th byte.
pub fn hide_secret(secret: &mut String, secret_offset: usize) {
    match secret.len().checked_sub(secret_offset) {
        None => (),
        Some(x) if x < 10 => {
            let offset = secret.ceil_char_boundary(secret_offset);
            secret.replace_range(offset.., "XXX...");
        }
        Some(x) if x < 20 => {
            let offset = secret.ceil_char_boundary(secret_offset + 2);
            secret.replace_range(offset.., "XXXX...");
        }
        Some(x) if x < 30 => {
            let offset = secret.ceil_char_boundary(secret_offset + 3);
            secret.replace_range(offset.., "XXXXX...");
        }
        Some(_x) => {
            let offset = secret.ceil_char_boundary(secret_offset + 5);
            secret.replace_range(offset.., "XXXXXX...");
        }
    }
}

impl Settings<Checked> {
    pub fn cleared() -> Settings<Checked> {
        Settings {
            displayed_attributes: Setting::Reset.into(),
            searchable_attributes: Setting::Reset.into(),
            filterable_attributes: Setting::Reset,
            foreign_keys: Setting::Reset,
            sortable_attributes: Setting::Reset,
            ranking_rules: Setting::Reset,
            stop_words: Setting::Reset,
            synonyms: Setting::Reset,
            non_separator_tokens: Setting::Reset,
            separator_tokens: Setting::Reset,
            dictionary: Setting::Reset,
            distinct_attribute: Setting::Reset,
            proximity_precision: Setting::Reset,
            typo_tolerance: Setting::Reset,
            faceting: Setting::Reset,
            pagination: Setting::Reset,
            embedders: Setting::Reset,
            search_cutoff_ms: Setting::Reset,
            localized_attributes: Setting::Reset,
            facet_search: Setting::Reset,
            prefix_search: Setting::Reset,
            chat: Setting::Reset,
            _kind: PhantomData,
        }
    }

    pub fn into_unchecked(self) -> Settings<Unchecked> {
        let Self {
            displayed_attributes,
            searchable_attributes,
            filterable_attributes,
            foreign_keys,
            sortable_attributes,
            ranking_rules,
            stop_words,
            non_separator_tokens,
            separator_tokens,
            dictionary,
            synonyms,
            distinct_attribute,
            proximity_precision,
            typo_tolerance,
            faceting,
            pagination,
            embedders,
            search_cutoff_ms,
            localized_attributes,
            facet_search,
            prefix_search,
            chat,
            _kind,
        } = self;

        Settings {
            displayed_attributes,
            searchable_attributes,
            filterable_attributes,
            sortable_attributes,
            foreign_keys,
            ranking_rules,
            stop_words,
            non_separator_tokens,
            separator_tokens,
            dictionary,
            synonyms,
            distinct_attribute,
            proximity_precision,
            typo_tolerance,
            faceting,
            pagination,
            embedders,
            search_cutoff_ms,
            localized_attributes,
            facet_search,
            prefix_search,
            chat,
            _kind: PhantomData,
        }
    }
}

impl Settings<Unchecked> {
    pub fn check(self) -> Settings<Checked> {
        let displayed_attributes = match self.displayed_attributes.0 {
            Setting::Set(fields) => {
                if fields.iter().any(|f| f == "*") {
                    Setting::Reset
                } else {
                    Setting::Set(fields)
                }
            }
            otherwise => otherwise,
        };

        let searchable_attributes = match self.searchable_attributes.0 {
            Setting::Set(fields) => {
                if fields.iter().any(|f| f == "*") {
                    Setting::Reset
                } else {
                    Setting::Set(fields)
                }
            }
            otherwise => otherwise,
        };

        Settings {
            displayed_attributes: displayed_attributes.into(),
            searchable_attributes: searchable_attributes.into(),
            filterable_attributes: self.filterable_attributes,
            foreign_keys: self.foreign_keys,
            sortable_attributes: self.sortable_attributes,
            ranking_rules: self.ranking_rules,
            stop_words: self.stop_words,
            synonyms: self.synonyms,
            non_separator_tokens: self.non_separator_tokens,
            separator_tokens: self.separator_tokens,
            dictionary: self.dictionary,
            distinct_attribute: self.distinct_attribute,
            proximity_precision: self.proximity_precision,
            typo_tolerance: self.typo_tolerance,
            faceting: self.faceting,
            pagination: self.pagination,
            embedders: self.embedders,
            search_cutoff_ms: self.search_cutoff_ms,
            localized_attributes: self.localized_attributes,
            facet_search: self.facet_search,
            prefix_search: self.prefix_search,
            chat: self.chat,
            _kind: PhantomData,
        }
    }

    pub fn validate(self) -> Result<Self, milli::Error> {
        self.validate_ranking_rules_settings()?.validate_embedding_settings()
    }

    fn validate_ranking_rules_settings(self) -> Result<Self, milli::Error> {
        let Setting::Set(ranking_rules) = self.ranking_rules.as_ref() else { return Ok(self) };

        let mut attribute = false;
        let mut attribute_rank_or_position = false;

        for rule in ranking_rules {
            attribute |= matches!(rule, RankingRuleView::Attribute);
            attribute_rank_or_position |=
                matches!(rule, RankingRuleView::AttributeRank | RankingRuleView::WordPosition);
        }

        if attribute && attribute_rank_or_position {
            return Err(milli::Error::UserError(milli::UserError::MixedAttributeRankingRulesUsage));
        }

        Ok(self)
    }

    fn validate_embedding_settings(mut self) -> Result<Self, milli::Error> {
        let Setting::Set(mut configs) = self.embedders else { return Ok(self) };
        for (name, config) in configs.iter_mut() {
            let config_to_check = std::mem::take(config);
            let checked_config = milli::update::validate_embedding_settings(
                config_to_check.inner,
                name,
                milli::vector::settings::EmbeddingValidationContext::SettingsPartialUpdate,
            )?;
            *config = SettingEmbeddingSettings { inner: checked_config };
        }
        self.embedders = Setting::Set(configs);
        Ok(self)
    }

    pub fn merge(&mut self, other: &Self) {
        // For most settings only the latest version is kept
        *self = Self {
            displayed_attributes: other
                .displayed_attributes
                .clone()
                .or(self.displayed_attributes.clone()),
            searchable_attributes: other
                .searchable_attributes
                .clone()
                .or(self.searchable_attributes.clone()),
            filterable_attributes: other
                .filterable_attributes
                .clone()
                .or(self.filterable_attributes.clone()),
            sortable_attributes: other
                .sortable_attributes
                .clone()
                .or(self.sortable_attributes.clone()),
            foreign_keys: other.foreign_keys.clone().or(self.foreign_keys.clone()),
            ranking_rules: other.ranking_rules.clone().or(self.ranking_rules.clone()),
            stop_words: other.stop_words.clone().or(self.stop_words.clone()),
            non_separator_tokens: other
                .non_separator_tokens
                .clone()
                .or(self.non_separator_tokens.clone()),
            separator_tokens: other.separator_tokens.clone().or(self.separator_tokens.clone()),
            dictionary: other.dictionary.clone().or(self.dictionary.clone()),
            synonyms: other.synonyms.clone().or(self.synonyms.clone()),
            distinct_attribute: other
                .distinct_attribute
                .clone()
                .or(self.distinct_attribute.clone()),
            proximity_precision: other.proximity_precision.or(self.proximity_precision),
            typo_tolerance: other.typo_tolerance.clone().or(self.typo_tolerance.clone()),
            faceting: other.faceting.clone().or(self.faceting.clone()),
            pagination: other.pagination.clone().or(self.pagination.clone()),
            search_cutoff_ms: other.search_cutoff_ms.or(self.search_cutoff_ms),
            localized_attributes: other
                .localized_attributes
                .clone()
                .or(self.localized_attributes.clone()),
            embedders: match (self.embedders.clone(), other.embedders.clone()) {
                (Setting::NotSet, set) | (set, Setting::NotSet) => set,
                (Setting::Set(_) | Setting::Reset, Setting::Reset) => Setting::Reset,
                (Setting::Reset, Setting::Set(embedder)) => Setting::Set(embedder),

                // If both are set we must merge the embeddings settings
                (Setting::Set(mut this), Setting::Set(other)) => {
                    for (k, v) in other {
                        this.insert(k, v);
                    }
                    Setting::Set(this)
                }
            },
            facet_search: other.facet_search.or(self.facet_search),
            prefix_search: other.prefix_search.or(self.prefix_search),
            chat: other.chat.clone().or(self.chat.clone()),
            _kind: PhantomData,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
pub struct Facets {
    pub level_group_size: Option<NonZeroUsize>,
    pub min_level_size: Option<NonZeroUsize>,
}

pub fn apply_settings_to_builder(
    settings: &Settings<Checked>,
    builder: &mut milli::update::Settings,
) {
    let Settings {
        displayed_attributes,
        searchable_attributes,
        filterable_attributes,
        sortable_attributes,
        foreign_keys,
        ranking_rules,
        stop_words,
        non_separator_tokens,
        separator_tokens,
        dictionary,
        synonyms,
        distinct_attribute,
        proximity_precision,
        typo_tolerance,
        faceting,
        pagination,
        embedders,
        search_cutoff_ms,
        localized_attributes: localized_attributes_rules,
        facet_search,
        prefix_search,
        chat,
        _kind,
    } = settings;

    match searchable_attributes.deref() {
        Setting::Set(ref names) => builder.set_searchable_fields(names.clone()),
        Setting::Reset => builder.reset_searchable_fields(),
        Setting::NotSet => (),
    }

    match displayed_attributes.deref() {
        Setting::Set(ref names) => builder.set_displayed_fields(names.clone()),
        Setting::Reset => builder.reset_displayed_fields(),
        Setting::NotSet => (),
    }

    match filterable_attributes {
        Setting::Set(ref facets) => {
            builder.set_filterable_fields(facets.clone().into_iter().collect())
        }
        Setting::Reset => builder.reset_filterable_fields(),
        Setting::NotSet => (),
    }

    match sortable_attributes {
        Setting::Set(ref fields) => builder.set_sortable_fields(fields.iter().cloned().collect()),
        Setting::Reset => builder.reset_sortable_fields(),
        Setting::NotSet => (),
    }

    match foreign_keys {
        Setting::Set(ref keys) => builder.set_foreign_keys(keys.clone().into_iter().collect()),
        Setting::Reset => builder.reset_foreign_keys(),
        Setting::NotSet => (),
    }

    match ranking_rules {
        Setting::Set(ref criteria) => {
            builder.set_criteria(criteria.iter().map(|c| c.clone().into()).collect())
        }
        Setting::Reset => builder.reset_criteria(),
        Setting::NotSet => (),
    }

    match stop_words {
        Setting::Set(ref stop_words) => builder.set_stop_words(stop_words.clone()),
        Setting::Reset => builder.reset_stop_words(),
        Setting::NotSet => (),
    }

    match non_separator_tokens {
        Setting::Set(ref non_separator_tokens) => {
            builder.set_non_separator_tokens(non_separator_tokens.clone())
        }
        Setting::Reset => builder.reset_non_separator_tokens(),
        Setting::NotSet => (),
    }

    match separator_tokens {
        Setting::Set(ref separator_tokens) => {
            builder.set_separator_tokens(separator_tokens.clone())
        }
        Setting::Reset => builder.reset_separator_tokens(),
        Setting::NotSet => (),
    }

    match dictionary {
        Setting::Set(ref dictionary) => builder.set_dictionary(dictionary.clone()),
        Setting::Reset => builder.reset_dictionary(),
        Setting::NotSet => (),
    }

    match synonyms {
        Setting::Set(ref synonyms) => builder.set_synonyms(synonyms.clone().into_iter().collect()),
        Setting::Reset => builder.reset_synonyms(),
        Setting::NotSet => (),
    }

    match distinct_attribute {
        Setting::Set(ref attr) => builder.set_distinct_field(attr.clone()),
        Setting::Reset => builder.reset_distinct_field(),
        Setting::NotSet => (),
    }

    match proximity_precision {
        Setting::Set(ref precision) => builder.set_proximity_precision((*precision).into()),
        Setting::Reset => builder.reset_proximity_precision(),
        Setting::NotSet => (),
    }

    match localized_attributes_rules {
        Setting::Set(ref rules) => builder
            .set_localized_attributes_rules(rules.iter().cloned().map(|r| r.into()).collect()),
        Setting::Reset => builder.reset_localized_attributes_rules(),
        Setting::NotSet => (),
    }

    match typo_tolerance {
        Setting::Set(ref value) => {
            match value.enabled {
                Setting::Set(val) => builder.set_authorize_typos(val),
                Setting::Reset => builder.reset_authorize_typos(),
                Setting::NotSet => (),
            }

            match value.min_word_size_for_typos {
                Setting::Set(ref setting) => {
                    match setting.one_typo {
                        Setting::Set(val) => builder.set_min_word_len_one_typo(val),
                        Setting::Reset => builder.reset_min_word_len_one_typo(),
                        Setting::NotSet => (),
                    }
                    match setting.two_typos {
                        Setting::Set(val) => builder.set_min_word_len_two_typos(val),
                        Setting::Reset => builder.reset_min_word_len_two_typos(),
                        Setting::NotSet => (),
                    }
                }
                Setting::Reset => {
                    builder.reset_min_word_len_one_typo();
                    builder.reset_min_word_len_two_typos();
                }
                Setting::NotSet => (),
            }

            match value.disable_on_words {
                Setting::Set(ref words) => {
                    builder.set_exact_words(words.clone());
                }
                Setting::Reset => builder.reset_exact_words(),
                Setting::NotSet => (),
            }

            match value.disable_on_attributes {
                Setting::Set(ref words) => {
                    builder.set_exact_attributes(words.iter().cloned().collect())
                }
                Setting::Reset => builder.reset_exact_attributes(),
                Setting::NotSet => (),
            }

            match value.disable_on_numbers {
                Setting::Set(val) => builder.set_disable_on_numbers(val),
                Setting::Reset => builder.reset_disable_on_numbers(),
                Setting::NotSet => (),
            }
        }
        Setting::Reset => {
            // all typo settings need to be reset here.
            builder.reset_authorize_typos();
            builder.reset_min_word_len_one_typo();
            builder.reset_min_word_len_two_typos();
            builder.reset_exact_words();
            builder.reset_exact_attributes();
            builder.reset_disable_on_numbers();
        }
        Setting::NotSet => (),
    }

    match faceting {
        Setting::Set(FacetingSettings { max_values_per_facet, sort_facet_values_by }) => {
            match max_values_per_facet {
                Setting::Set(val) => builder.set_max_values_per_facet(*val),
                Setting::Reset => builder.reset_max_values_per_facet(),
                Setting::NotSet => (),
            }
            match sort_facet_values_by {
                Setting::Set(val) => builder.set_sort_facet_values_by(
                    val.iter().map(|(name, order)| (name.clone(), (*order).into())).collect(),
                ),
                Setting::Reset => builder.reset_sort_facet_values_by(),
                Setting::NotSet => (),
            }
        }
        Setting::Reset => {
            builder.reset_max_values_per_facet();
            builder.reset_sort_facet_values_by();
        }
        Setting::NotSet => (),
    }

    match pagination {
        Setting::Set(ref value) => match value.max_total_hits {
            Setting::Set(val) => builder.set_pagination_max_total_hits(val.into()),
            Setting::Reset => builder.reset_pagination_max_total_hits(),
            Setting::NotSet => (),
        },
        Setting::Reset => builder.reset_pagination_max_total_hits(),
        Setting::NotSet => (),
    }

    match embedders {
        Setting::Set(value) => builder.set_embedder_settings(
            value.iter().map(|(k, v)| (k.clone(), v.inner.clone())).collect(),
        ),
        Setting::Reset => builder.reset_embedder_settings(),
        Setting::NotSet => (),
    }

    match search_cutoff_ms {
        Setting::Set(cutoff) => builder.set_search_cutoff(*cutoff),
        Setting::Reset => builder.reset_search_cutoff(),
        Setting::NotSet => (),
    }

    match prefix_search {
        Setting::Set(prefix_search) => {
            builder.set_prefix_search(PrefixSearch::from(*prefix_search))
        }
        Setting::Reset => builder.reset_prefix_search(),
        Setting::NotSet => (),
    }

    match facet_search {
        Setting::Set(facet_search) => builder.set_facet_search(*facet_search),
        Setting::Reset => builder.reset_facet_search(),
        Setting::NotSet => (),
    }

    match chat {
        Setting::Set(chat) => builder.set_chat(chat.clone()),
        Setting::Reset => builder.reset_chat(),
        Setting::NotSet => (),
    }
}

pub enum SecretPolicy {
    RevealSecrets,
    HideSecrets,
}

pub fn settings(
    index: &Index,
    rtxn: &crate::heed::RoTxn,
    secret_policy: SecretPolicy,
) -> Result<Settings<Checked>, milli::Error> {
    let displayed_attributes =
        index.displayed_fields(rtxn)?.map(|fields| fields.into_iter().map(String::from).collect());

    let searchable_attributes = index
        .user_defined_searchable_fields(rtxn)?
        .map(|fields| fields.into_iter().map(String::from).collect());

    let filterable_attributes = index.filterable_attributes_rules(rtxn)?.into_iter().collect();

    let sortable_attributes = index.sortable_fields(rtxn)?.into_iter().collect();

    let foreign_keys = index.foreign_keys(rtxn)?.into_iter().collect();

    let criteria = index.criteria(rtxn)?;

    let stop_words = index
        .stop_words(rtxn)?
        .map(|stop_words| -> Result<BTreeSet<_>, milli::Error> {
            Ok(stop_words.stream().into_strs()?.into_iter().collect())
        })
        .transpose()?
        .unwrap_or_default();

    let non_separator_tokens = index.non_separator_tokens(rtxn)?.unwrap_or_default();
    let separator_tokens = index.separator_tokens(rtxn)?.unwrap_or_default();
    let dictionary = index.dictionary(rtxn)?.unwrap_or_default();

    let distinct_field = index.distinct_field(rtxn)?.map(String::from);

    let proximity_precision = index.proximity_precision(rtxn)?.map(ProximityPrecisionView::from);

    let synonyms = index.user_defined_synonyms(rtxn)?;

    let min_typo_word_len = MinWordSizeTyposSetting {
        one_typo: Setting::Set(index.min_word_len_one_typo(rtxn)?),
        two_typos: Setting::Set(index.min_word_len_two_typos(rtxn)?),
    };

    let disabled_words = match index.exact_words(rtxn)? {
        Some(fst) => fst.into_stream().into_strs()?.into_iter().collect(),
        None => BTreeSet::new(),
    };

    let disabled_attributes = index.exact_attributes(rtxn)?.into_iter().map(String::from).collect();
    let DisabledTyposTerms { disable_on_numbers } = index.disabled_typos_terms(rtxn)?;

    let typo_tolerance = TypoSettings {
        enabled: Setting::Set(index.authorize_typos(rtxn)?),
        min_word_size_for_typos: Setting::Set(min_typo_word_len),
        disable_on_words: Setting::Set(disabled_words),
        disable_on_attributes: Setting::Set(disabled_attributes),
        disable_on_numbers: Setting::Set(disable_on_numbers),
    };

    let faceting = FacetingSettings {
        max_values_per_facet: Setting::Set(
            index
                .max_values_per_facet(rtxn)?
                .map(|x| x as usize)
                .unwrap_or(DEFAULT_VALUES_PER_FACET),
        ),
        sort_facet_values_by: Setting::Set(
            index
                .sort_facet_values_by(rtxn)?
                .into_iter()
                .map(|(name, sort)| (name, sort.into()))
                .collect(),
        ),
    };

    let pagination = PaginationSettings {
        max_total_hits: Setting::Set(
            index
                .pagination_max_total_hits(rtxn)?
                .and_then(|x| (x as usize).try_into().ok())
                .unwrap_or(NonZeroUsize::new(DEFAULT_PAGINATION_MAX_TOTAL_HITS).unwrap()),
        ),
    };

    let embedders: BTreeMap<_, _> = index
        .embedding_configs()
        .embedding_configs(rtxn)?
        .into_iter()
        .map(|IndexEmbeddingConfig { name, config, .. }| {
            (name, SettingEmbeddingSettings { inner: Setting::Set(config.into()) })
        })
        .collect();

    let embedders = Setting::Set(embedders);
    let search_cutoff_ms = index.search_cutoff(rtxn)?;
    let localized_attributes_rules = index.localized_attributes_rules(rtxn)?;
    let prefix_search = index.prefix_search(rtxn)?.map(PrefixSearchSettings::from);
    let facet_search = index.facet_search(rtxn)?;
    let chat = index.chat_config(rtxn).map(ChatSettings::from)?;

    let mut settings = Settings {
        displayed_attributes: match displayed_attributes {
            Some(attrs) => Setting::Set(attrs),
            None => Setting::Reset,
        }
        .into(),
        searchable_attributes: match searchable_attributes {
            Some(attrs) => Setting::Set(attrs),
            None => Setting::Reset,
        }
        .into(),
        filterable_attributes: Setting::Set(filterable_attributes),
        sortable_attributes: Setting::Set(sortable_attributes),
        foreign_keys: Setting::Set(foreign_keys),
        ranking_rules: Setting::Set(criteria.iter().map(|c| c.clone().into()).collect()),
        stop_words: Setting::Set(stop_words),
        non_separator_tokens: Setting::Set(non_separator_tokens),
        separator_tokens: Setting::Set(separator_tokens),
        dictionary: Setting::Set(dictionary),
        distinct_attribute: match distinct_field {
            Some(field) => Setting::Set(field),
            None => Setting::Reset,
        },
        proximity_precision: Setting::Set(proximity_precision.unwrap_or_default()),
        synonyms: Setting::Set(synonyms),
        typo_tolerance: Setting::Set(typo_tolerance),
        faceting: Setting::Set(faceting),
        pagination: Setting::Set(pagination),
        embedders,
        search_cutoff_ms: match search_cutoff_ms {
            Some(cutoff) => Setting::Set(cutoff),
            None => Setting::Reset,
        },
        localized_attributes: match localized_attributes_rules {
            Some(rules) => Setting::Set(rules.into_iter().map(|r| r.into()).collect()),
            None => Setting::Reset,
        },
        facet_search: Setting::Set(facet_search),
        prefix_search: Setting::Set(prefix_search.unwrap_or_default()),
        chat: Setting::Set(chat),
        _kind: PhantomData,
    };

    if let SecretPolicy::HideSecrets = secret_policy {
        settings.hide_secrets()
    }

    Ok(settings)
}

#[derive(Debug, Clone, PartialEq, Eq, Deserr, ToSchema)]
#[deserr(try_from(&String) = FromStr::from_str -> CriterionError)]
pub enum RankingRuleView {
    /// Sorted by decreasing number of matched query terms.
    Words,
    /// Sorted by increasing number of typos.
    Typo,
    /// Sorted by increasing distance between matched query terms.
    Proximity,
    /// Documents with query words contained in more important
    /// attributes and at a closer-to-the-front position in it
    /// are considered better.
    Attribute,
    /// Documents with query words contained in more important
    /// attributes are considered better. Position of the
    /// query words in an attribute is not considered.
    AttributeRank,
    /// Documents with query words that are closer to the front
    /// of an attribute are considered better. Attribute rank
    /// is not considered.
    WordPosition,
    /// Dynamically sort at query time the documents. None, one or multiple
    /// Asc/Desc sortable attributes can be used in place of this criterion at
    /// query time.
    Sort,
    /// Sorted by the similarity of the matched words with the query words.
    Exactness,
    /// Sorted by the increasing value of the field specified.
    Asc(String),
    /// Sorted by the decreasing value of the field specified.
    Desc(String),
}

impl Serialize for RankingRuleView {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{}", Criterion::from(self.clone())))
    }
}

impl<'de> Deserialize<'de> for RankingRuleView {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {
            type Value = RankingRuleView;
            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(formatter, "the name of a valid ranking rule (string)")
            }
            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                let criterion = Criterion::from_str(v).map_err(|_| {
                    E::invalid_value(serde::de::Unexpected::Str(v), &"a valid ranking rule")
                })?;
                Ok(RankingRuleView::from(criterion))
            }
        }
        deserializer.deserialize_str(Visitor)
    }
}
impl FromStr for RankingRuleView {
    type Err = <Criterion as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(RankingRuleView::from(Criterion::from_str(s)?))
    }
}
impl fmt::Display for RankingRuleView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt::Display::fmt(&Criterion::from(self.clone()), f)
    }
}
impl From<Criterion> for RankingRuleView {
    fn from(value: Criterion) -> Self {
        match value {
            Criterion::Words => RankingRuleView::Words,
            Criterion::Typo => RankingRuleView::Typo,
            Criterion::Proximity => RankingRuleView::Proximity,
            Criterion::Attribute => RankingRuleView::Attribute,
            Criterion::AttributeRank => RankingRuleView::AttributeRank,
            Criterion::WordPosition => RankingRuleView::WordPosition,
            Criterion::Sort => RankingRuleView::Sort,
            Criterion::Exactness => RankingRuleView::Exactness,
            Criterion::Asc(x) => RankingRuleView::Asc(x),
            Criterion::Desc(x) => RankingRuleView::Desc(x),
        }
    }
}
impl From<RankingRuleView> for Criterion {
    fn from(value: RankingRuleView) -> Self {
        match value {
            RankingRuleView::Words => Criterion::Words,
            RankingRuleView::Typo => Criterion::Typo,
            RankingRuleView::Proximity => Criterion::Proximity,
            RankingRuleView::Attribute => Criterion::Attribute,
            RankingRuleView::AttributeRank => Criterion::AttributeRank,
            RankingRuleView::WordPosition => Criterion::WordPosition,
            RankingRuleView::Sort => Criterion::Sort,
            RankingRuleView::Exactness => Criterion::Exactness,
            RankingRuleView::Asc(x) => Criterion::Asc(x),
            RankingRuleView::Desc(x) => Criterion::Desc(x),
        }
    }
}

#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Deserr, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
#[deserr(error = DeserrJsonError<InvalidSettingsProximityPrecision>, rename_all = camelCase, deny_unknown_fields)]
pub enum ProximityPrecisionView {
    #[default]
    ByWord,
    ByAttribute,
}

impl From<ProximityPrecision> for ProximityPrecisionView {
    fn from(value: ProximityPrecision) -> Self {
        match value {
            ProximityPrecision::ByWord => ProximityPrecisionView::ByWord,
            ProximityPrecision::ByAttribute => ProximityPrecisionView::ByAttribute,
        }
    }
}
impl From<ProximityPrecisionView> for ProximityPrecision {
    fn from(value: ProximityPrecisionView) -> Self {
        match value {
            ProximityPrecisionView::ByWord => ProximityPrecision::ByWord,
            ProximityPrecisionView::ByAttribute => ProximityPrecision::ByAttribute,
        }
    }
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct WildcardSetting(Setting<Vec<String>>);

impl WildcardSetting {
    pub fn or(self, other: Self) -> Self {
        Self(self.0.or(other.0))
    }
}

impl From<Setting<Vec<String>>> for WildcardSetting {
    fn from(setting: Setting<Vec<String>>) -> Self {
        Self(setting)
    }
}

impl Serialize for WildcardSetting {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_with_wildcard(&self.0, serializer)
    }
}

impl<E: deserr::DeserializeError> Deserr<E> for WildcardSetting {
    fn deserialize_from_value<V: deserr::IntoValue>(
        value: deserr::Value<V>,
        location: ValuePointerRef<'_>,
    ) -> Result<Self, E> {
        Ok(Self(Setting::deserialize_from_value(value, location)?))
    }
}

impl std::ops::Deref for WildcardSetting {
    type Target = Setting<Vec<String>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Deserr, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
#[schema(rename_all = "camelCase")]
#[deserr(error = DeserrJsonError<InvalidSettingsPrefixSearch>, rename_all = camelCase, deny_unknown_fields)]
pub enum PrefixSearchSettings {
    #[default]
    IndexingTime,
    Disabled,
}

impl From<PrefixSearch> for PrefixSearchSettings {
    fn from(value: PrefixSearch) -> Self {
        match value {
            PrefixSearch::IndexingTime => PrefixSearchSettings::IndexingTime,
            PrefixSearch::Disabled => PrefixSearchSettings::Disabled,
        }
    }
}
impl From<PrefixSearchSettings> for PrefixSearch {
    fn from(value: PrefixSearchSettings) -> Self {
        match value {
            PrefixSearchSettings::IndexingTime => PrefixSearch::IndexingTime,
            PrefixSearchSettings::Disabled => PrefixSearch::Disabled,
        }
    }
}

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

    #[test]
    fn test_setting_check() {
        // test no changes
        let settings = Settings {
            displayed_attributes: Setting::Set(vec![String::from("hello")]).into(),
            searchable_attributes: Setting::Set(vec![String::from("hello")]).into(),
            filterable_attributes: Setting::NotSet,
            sortable_attributes: Setting::NotSet,
            foreign_keys: Setting::NotSet,
            ranking_rules: Setting::NotSet,
            stop_words: Setting::NotSet,
            non_separator_tokens: Setting::NotSet,
            separator_tokens: Setting::NotSet,
            dictionary: Setting::NotSet,
            synonyms: Setting::NotSet,
            distinct_attribute: Setting::NotSet,
            proximity_precision: Setting::NotSet,
            typo_tolerance: Setting::NotSet,
            faceting: Setting::NotSet,
            pagination: Setting::NotSet,
            embedders: Setting::NotSet,
            localized_attributes: Setting::NotSet,
            search_cutoff_ms: Setting::NotSet,
            facet_search: Setting::NotSet,
            prefix_search: Setting::NotSet,
            chat: Setting::NotSet,
            _kind: PhantomData::<Unchecked>,
        };

        let checked = settings.clone().check();
        assert_eq!(settings.displayed_attributes, checked.displayed_attributes);
        assert_eq!(settings.searchable_attributes, checked.searchable_attributes);

        // test wildcard
        // test no changes
        let settings = Settings {
            displayed_attributes: Setting::Set(vec![String::from("*")]).into(),
            searchable_attributes: Setting::Set(vec![String::from("hello"), String::from("*")])
                .into(),
            filterable_attributes: Setting::NotSet,
            sortable_attributes: Setting::NotSet,
            foreign_keys: Setting::NotSet,
            ranking_rules: Setting::NotSet,
            stop_words: Setting::NotSet,
            non_separator_tokens: Setting::NotSet,
            separator_tokens: Setting::NotSet,
            dictionary: Setting::NotSet,
            synonyms: Setting::NotSet,
            distinct_attribute: Setting::NotSet,
            proximity_precision: Setting::NotSet,
            typo_tolerance: Setting::NotSet,
            faceting: Setting::NotSet,
            pagination: Setting::NotSet,
            embedders: Setting::NotSet,
            localized_attributes: Setting::NotSet,
            search_cutoff_ms: Setting::NotSet,
            facet_search: Setting::NotSet,
            prefix_search: Setting::NotSet,
            chat: Setting::NotSet,

            _kind: PhantomData::<Unchecked>,
        };

        let checked = settings.check();
        assert_eq!(checked.displayed_attributes, Setting::Reset.into());
        assert_eq!(checked.searchable_attributes, Setting::Reset.into());
    }

    #[test]
    fn test_hide_secret() {
        let mut secret = String::from("123456789");
        hide_secret(&mut secret, 0);
        assert_eq!(secret, "XXX...");
        let mut secret = String::from("123456789012345678901234567890");
        hide_secret(&mut secret, 0);
        assert_eq!(secret, "12345XXXXXX...");

        // related to https://linear.app/meilisearch/issue/SP-1771
        let mut secret = String::from("ひらがな6789012345678901234567890");
        hide_secret(&mut secret, 0);
        assert_eq!(secret, "ひらXXXXXX...");
    }
}
