// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Artifact<'a> {
    ///An optional description of this artifact.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///The downloadable binary.
    #[serde(borrow)]
    pub download: BlobRef<'a>,
    ///Optional tags describing this artifact, e.g. 'aarch64', 'apple-darwin', 'linux'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
}

/// A distribution of an application.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Distribution<'a> {
    ///The list of downloadable artifacts for this distribution.
    #[serde(borrow)]
    pub artifacts: Vec<distribution::Artifact<'a>>,
    ///An optional description of this distribution.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///The version of this distribution, e.g. '0.14.0'.
    #[serde(borrow)]
    pub version: CowStr<'a>,
}

/// 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<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Distribution<'a>,
}

impl<'a> Distribution<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, DistributionRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

impl<'a> LexiconSchema for Artifact<'a> {
    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<'de> = DistributionGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<DistributionGetRecordOutput<'_>> for Distribution<'_> {
    fn from(output: DistributionGetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

impl Collection for Distribution<'_> {
    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<'a> LexiconSchema for Distribution<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDownload<S> {}
    impl<S: State> State for SetDownload<S> {
        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<'a, S: artifact_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<BlobRef<'a>>, Option<Vec<CowStr<'a>>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S: artifact_state::State> ArtifactBuilder<'a, S> {
    /// Set the `tags` field (optional)
    pub fn tags(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> 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<CowStr<'a>>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S> ArtifactBuilder<'a, S>
where
    S: artifact_state::State,
    S::Download: artifact_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Artifact<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Artifact<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetArtifacts<S> {}
    impl<S: State> State for SetArtifacts<S> {
        type Artifacts = Set<members::artifacts>;
        type Version = S::Version;
    }
    ///State transition - sets the `version` field to Set
    pub struct SetVersion<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetVersion<S> {}
    impl<S: State> State for SetVersion<S> {
        type Artifacts = S::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<'a, S: distribution_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<distribution::Artifact<'a>>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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

impl<'a, S> DistributionBuilder<'a, S>
where
    S: distribution_state::State,
    S::Artifacts: distribution_state::IsSet,
    S::Version: distribution_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Distribution<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Distribution<'a> {
        Distribution {
            artifacts: self._fields.0.unwrap(),
            description: self._fields.1,
            version: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}