// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.hypercerts.helper.workScopeTag
//
// 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon, open_union};
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::com_atproto::repo::strong_ref::StrongRef;
use crate::org_hypercerts::SmallBlob;
use crate::org_hypercerts::Uri;
/// A reusable scope atom for work scope logic expressions. Scopes can represent topics, languages, domains, deliverables, methods, regions, tags, or other categorical labels.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "org.hypercerts.helper.workScopeTag",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct WorkScopeTag<S: BosStr = DefaultStr> {
    ///Optional array of alternative names or identifiers for this scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aliases: Option<Vec<S>>,
    ///Client-declared timestamp when this record was originally created
    pub created_at: Datetime,
    ///Optional longer description of this scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Optional external reference for this scope as a URI or blob.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_reference: Option<WorkScopeTagExternalReference<S>>,
    ///Lowercase, hyphenated machine-readable key for this scope (e.g., 'ipfs', 'go-lang', 'filecoin').
    pub key: S,
    ///Category type of this scope. Recommended values: topic, language, domain, method, tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<S>,
    ///Human-readable label for this scope.
    pub label: S,
    ///Optional strong reference to a parent scope record for taxonomy/hierarchy support.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent: Option<StrongRef<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum WorkScopeTagExternalReference<S: BosStr = DefaultStr> {
    #[serde(rename = "org.hypercerts.defs#uri")]
    Uri(Box<Uri<S>>),
    #[serde(rename = "org.hypercerts.defs#smallBlob")]
    SmallBlob(Box<SmallBlob<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 WorkScopeTagGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: WorkScopeTag<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct WorkScopeTagRecord;
impl XrpcResp for WorkScopeTagRecord {
    const NSID: &'static str = "org.hypercerts.helper.workScopeTag";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = WorkScopeTagGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for WorkScopeTag<S> {
    const NSID: &'static str = "org.hypercerts.helper.workScopeTag";
    type Record = WorkScopeTagRecord;
}

impl Collection for WorkScopeTagRecord {
    const NSID: &'static str = "org.hypercerts.helper.workScopeTag";
    type Record = WorkScopeTagRecord;
}

impl<S: BosStr> LexiconSchema for WorkScopeTag<S> {
    fn nsid() -> &'static str {
        "org.hypercerts.helper.workScopeTag"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_hypercerts_helper_workScopeTag()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.aliases {
            #[allow(unused_comparisons)]
            if value.len() > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("aliases"),
                    max: 50usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 1000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 1000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.key;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 120usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("key"),
                    max: 120usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.kind {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("kind"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.label;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 200usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("label"),
                    max: 200usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod work_scope_tag_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 CreatedAt;
        type Key;
        type Label;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Key = Unset;
        type Label = Unset;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCreatedAt<St> {}
    impl<St: State> State for SetCreatedAt<St> {
        type CreatedAt = Set<members::created_at>;
        type Key = St::Key;
        type Label = St::Label;
    }
    ///State transition - sets the `key` field to Set
    pub struct SetKey<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetKey<St> {}
    impl<St: State> State for SetKey<St> {
        type CreatedAt = St::CreatedAt;
        type Key = Set<members::key>;
        type Label = St::Label;
    }
    ///State transition - sets the `label` field to Set
    pub struct SetLabel<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLabel<St> {}
    impl<St: State> State for SetLabel<St> {
        type CreatedAt = St::CreatedAt;
        type Key = St::Key;
        type Label = Set<members::label>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `key` field
        pub struct key(());
        ///Marker type for the `label` field
        pub struct label(());
    }
}

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

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

impl<S: BosStr> WorkScopeTag<S> {
    /// Create a new builder for this type
    pub fn builder() -> WorkScopeTagBuilder<work_scope_tag_state::Empty, S> {
        WorkScopeTagBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> WorkScopeTagBuilder<St, S>
where
    St: work_scope_tag_state::State,
    St::CreatedAt: work_scope_tag_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> WorkScopeTagBuilder<work_scope_tag_state::SetCreatedAt<St>, S> {
        self._fields.1 = Option::Some(value.into());
        WorkScopeTagBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St: work_scope_tag_state::State, S: BosStr> WorkScopeTagBuilder<St, S> {
    /// Set the `externalReference` field (optional)
    pub fn external_reference(
        mut self,
        value: impl Into<Option<WorkScopeTagExternalReference<S>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `externalReference` field to an Option value (optional)
    pub fn maybe_external_reference(
        mut self,
        value: Option<WorkScopeTagExternalReference<S>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> WorkScopeTagBuilder<St, S>
where
    St: work_scope_tag_state::State,
    St::Key: work_scope_tag_state::IsUnset,
{
    /// Set the `key` field (required)
    pub fn key(
        mut self,
        value: impl Into<S>,
    ) -> WorkScopeTagBuilder<work_scope_tag_state::SetKey<St>, S> {
        self._fields.4 = Option::Some(value.into());
        WorkScopeTagBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: work_scope_tag_state::State, S: BosStr> WorkScopeTagBuilder<St, S> {
    /// Set the `kind` field (optional)
    pub fn kind(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `kind` field to an Option value (optional)
    pub fn maybe_kind(mut self, value: Option<S>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St, S: BosStr> WorkScopeTagBuilder<St, S>
where
    St: work_scope_tag_state::State,
    St::Label: work_scope_tag_state::IsUnset,
{
    /// Set the `label` field (required)
    pub fn label(
        mut self,
        value: impl Into<S>,
    ) -> WorkScopeTagBuilder<work_scope_tag_state::SetLabel<St>, S> {
        self._fields.6 = Option::Some(value.into());
        WorkScopeTagBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: work_scope_tag_state::State, S: BosStr> WorkScopeTagBuilder<St, S> {
    /// Set the `parent` field (optional)
    pub fn parent(mut self, value: impl Into<Option<StrongRef<S>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `parent` field to an Option value (optional)
    pub fn maybe_parent(mut self, value: Option<StrongRef<S>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St, S: BosStr> WorkScopeTagBuilder<St, S>
where
    St: work_scope_tag_state::State,
    St::CreatedAt: work_scope_tag_state::IsSet,
    St::Key: work_scope_tag_state::IsSet,
    St::Label: work_scope_tag_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> WorkScopeTag<S> {
        WorkScopeTag {
            aliases: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            external_reference: self._fields.3,
            key: self._fields.4.unwrap(),
            kind: self._fields.5,
            label: self._fields.6.unwrap(),
            parent: self._fields.7,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> WorkScopeTag<S> {
        WorkScopeTag {
            aliases: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            external_reference: self._fields.3,
            key: self._fields.4.unwrap(),
            kind: self._fields.5,
            label: self._fields.6.unwrap(),
            parent: self._fields.7,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_hypercerts_helper_workScopeTag() -> 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("org.hypercerts.helper.workScopeTag"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A reusable scope atom for work scope logic expressions. Scopes can represent topics, languages, domains, deliverables, methods, regions, tags, or other categorical labels.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("createdAt"),
                                SmolStr::new_static("key"), SmolStr::new_static("label")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("aliases"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional array of alternative names or identifiers for this scope.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(200usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when this record was originally created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional longer description of this scope.",
                                        ),
                                    ),
                                    max_length: Some(10000usize),
                                    max_graphemes: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("externalReference"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional external reference for this scope as a URI or blob.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("org.hypercerts.defs#uri"),
                                        CowStr::new_static("org.hypercerts.defs#smallBlob")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("key"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Lowercase, hyphenated machine-readable key for this scope (e.g., 'ipfs', 'go-lang', 'filecoin').",
                                        ),
                                    ),
                                    max_length: Some(120usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("kind"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Category type of this scope. Recommended values: topic, language, domain, method, tag.",
                                        ),
                                    ),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("label"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Human-readable label for this scope."),
                                    ),
                                    max_length: Some(200usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("parent"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}