// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: garden.lexicon.exultant-zebra.distribution
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::{CowStr, BosStr, DefaultStr, FromStaticStr};

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::deps::smol_str::SmolStr;
use jacquard_common::types::blob::BlobRef;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::garden_lexicon::exultant_zebra::distribution;
/// A downloadable artifact within a distribution.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Artifact<S: BosStr = DefaultStr> {
    ///An optional description of this artifact.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///The downloadable binary.
    pub download: BlobRef<S>,
    ///Optional tags describing this artifact, e.g. 'aarch64', 'apple-darwin', 'linux'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A distribution of an application.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "garden.lexicon.exultant-zebra.distribution",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Distribution<S: BosStr = DefaultStr> {
    ///The list of downloadable artifacts for this distribution.
    pub artifacts: Vec<distribution::Artifact<S>>,
    ///An optional description of this distribution.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///The version of this distribution, e.g. '0.14.0'.
    pub version: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct DistributionGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Distribution<S>,
}

impl<S: BosStr> Distribution<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, DistributionRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

impl<S: BosStr> LexiconSchema for Artifact<S> {
    fn nsid() -> &'static str {
        "garden.lexicon.exultant-zebra.distribution"
    }
    fn def_name() -> &'static str {
        "artifact"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_garden_lexicon_exultant_zebra_distribution()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.download;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["*/*"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("download"),
                        accepted: vec!["*/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

/// Marker type for deserializing records from this collection.

#[derive(Debug, Serialize, Deserialize)]
pub struct DistributionRecord;
impl XrpcResp for DistributionRecord {
    const NSID: &'static str = "garden.lexicon.exultant-zebra.distribution";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = DistributionGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<DistributionGetRecordOutput<S>> for Distribution<S> {
    fn from(output: DistributionGetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Distribution<S> {
    const NSID: &'static str = "garden.lexicon.exultant-zebra.distribution";
    type Record = DistributionRecord;
}

impl Collection for DistributionRecord {
    const NSID: &'static str = "garden.lexicon.exultant-zebra.distribution";
    type Record = DistributionRecord;
}

impl<S: BosStr> LexiconSchema for Distribution<S> {
    fn nsid() -> &'static str {
        "garden.lexicon.exultant-zebra.distribution"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_garden_lexicon_exultant_zebra_distribution()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

pub mod artifact_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Download;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Download = Unset;
    }
    ///State transition - sets the `download` field to Set
    pub struct SetDownload<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDownload<St> {}
    impl<St: State> State for SetDownload<St> {
        type Download = Set<members::download>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `download` field
        pub struct download(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ArtifactBuilder<St: artifact_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<BlobRef<S>>, Option<Vec<S>>),
    _type: PhantomData<fn() -> S>,
}

impl Artifact<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> ArtifactBuilder<artifact_state::Empty, DefaultStr> {
        ArtifactBuilder::new()
    }
}

impl<S: BosStr> Artifact<S> {
    /// Create a new builder for this type
    pub fn builder() -> ArtifactBuilder<artifact_state::Empty, S> {
        ArtifactBuilder::builder()
    }
}

impl ArtifactBuilder<artifact_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        ArtifactBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> ArtifactBuilder<artifact_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        ArtifactBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<St: artifact_state::State, S: BosStr> ArtifactBuilder<St, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> ArtifactBuilder<St, S>
where
    St: artifact_state::State,
    St::Download: artifact_state::IsUnset,
{
    /// Set the `download` field (required)
    pub fn download(
        mut self,
        value: impl Into<BlobRef<S>>,
    ) -> ArtifactBuilder<artifact_state::SetDownload<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ArtifactBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: artifact_state::State, S: BosStr> ArtifactBuilder<St, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `tags` field to an Option value (optional)
    pub fn maybe_tags(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> ArtifactBuilder<St, S>
where
    St: artifact_state::State,
    St::Download: artifact_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Artifact<S> {
        Artifact {
            description: self._fields.0,
            download: self._fields.1.unwrap(),
            tags: self._fields.2,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Artifact<S> {
        Artifact {
            description: self._fields.0,
            download: self._fields.1.unwrap(),
            tags: self._fields.2,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_garden_lexicon_exultant_zebra_distribution() -> LexiconDoc<'static> {
    #[allow(unused_imports)]
    use jacquard_common::{CowStr, deps::smol_str::SmolStr, types::blob::MimeType};
    use jacquard_lexicon::lexicon::*;
    use alloc::collections::BTreeMap;
    LexiconDoc {
        lexicon: Lexicon::Lexicon1,
        id: CowStr::new_static("garden.lexicon.exultant-zebra.distribution"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("artifact"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A downloadable artifact within a distribution.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("download")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("description"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "An optional description of this artifact.",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("download"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("tags"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "Optional tags describing this artifact, e.g. 'aarch64', 'apple-darwin', 'linux'.",
                                    ),
                                ),
                                items: LexArrayItem::String(LexString {
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A distribution of an application."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("version"),
                                SmolStr::new_static("artifacts")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("artifacts"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "The list of downloadable artifacts for this distribution.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#artifact"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "An optional description of this distribution.",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("version"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The version of this distribution, e.g. '0.14.0'.",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod distribution_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Artifacts;
        type Version;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Artifacts = Unset;
        type Version = Unset;
    }
    ///State transition - sets the `artifacts` field to Set
    pub struct SetArtifacts<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetArtifacts<St> {}
    impl<St: State> State for SetArtifacts<St> {
        type Artifacts = Set<members::artifacts>;
        type Version = St::Version;
    }
    ///State transition - sets the `version` field to Set
    pub struct SetVersion<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetVersion<St> {}
    impl<St: State> State for SetVersion<St> {
        type Artifacts = St::Artifacts;
        type Version = Set<members::version>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `artifacts` field
        pub struct artifacts(());
        ///Marker type for the `version` field
        pub struct version(());
    }
}

/// Builder for constructing an instance of this type.
pub struct DistributionBuilder<St: distribution_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<Vec<distribution::Artifact<S>>>, Option<S>, Option<S>),
    _type: PhantomData<fn() -> S>,
}

impl Distribution<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> DistributionBuilder<distribution_state::Empty, DefaultStr> {
        DistributionBuilder::new()
    }
}

impl<S: BosStr> Distribution<S> {
    /// Create a new builder for this type
    pub fn builder() -> DistributionBuilder<distribution_state::Empty, S> {
        DistributionBuilder::builder()
    }
}

impl DistributionBuilder<distribution_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        DistributionBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> DistributionBuilder<distribution_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        DistributionBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DistributionBuilder<St, S>
where
    St: distribution_state::State,
    St::Artifacts: distribution_state::IsUnset,
{
    /// Set the `artifacts` field (required)
    pub fn artifacts(
        mut self,
        value: impl Into<Vec<distribution::Artifact<S>>>,
    ) -> DistributionBuilder<distribution_state::SetArtifacts<St>, S> {
        self._fields.0 = Option::Some(value.into());
        DistributionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: distribution_state::State, S: BosStr> DistributionBuilder<St, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<S>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> DistributionBuilder<St, S>
where
    St: distribution_state::State,
    St::Version: distribution_state::IsUnset,
{
    /// Set the `version` field (required)
    pub fn version(
        mut self,
        value: impl Into<S>,
    ) -> DistributionBuilder<distribution_state::SetVersion<St>, S> {
        self._fields.2 = Option::Some(value.into());
        DistributionBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DistributionBuilder<St, S>
where
    St: distribution_state::State,
    St::Artifacts: distribution_state::IsSet,
    St::Version: distribution_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Distribution<S> {
        Distribution {
            artifacts: self._fields.0.unwrap(),
            description: self._fields.1,
            version: self._fields.2.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Distribution<S> {
        Distribution {
            artifacts: self._fields.0.unwrap(),
            description: self._fields.1,
            version: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}