// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.hypercerts.workscope.tag
//
// 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, UriValue};
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. Tags are composed into structured expressions via CEL (Common Expression Language) on activity records.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "org.hypercerts.workscope.tag",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Tag<S: BosStr = DefaultStr> {
    ///Alternative human-readable names for this scope (e.g., translations, abbreviations, or common synonyms). Unlike sameAs, these are plain-text labels, not links to external ontologies.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aliases: Option<Vec<S>>,
    ///Category type of this scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<TagCategory<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>,
    ///Lowercase, underscore-separated machine-readable key for this scope (e.g., 'mangrove_restoration', 'biodiversity_monitoring'). Used as the canonical identifier in CEL expressions.
    pub key: S,
    ///Human-readable name for this scope.
    pub name: S,
    ///Optional strong reference to a parent work scope tag record for taxonomy/hierarchy support. The record referenced must conform with the lexicon org.hypercerts.workscope.tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent: Option<StrongRef<S>>,
    ///Link to a governance or reference document where this work scope tag is defined and further explained.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reference_document: Option<TagReferenceDocument<S>>,
    ///URIs to semantically equivalent concepts in external ontologies or taxonomies (e.g., Wikidata QIDs, ENVO terms, SDG targets). Used for interoperability, not as documentation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub same_as: Option<Vec<UriValue<S>>>,
    ///Lifecycle status of this tag. Communities propose tags, curators accept them, deprecated tags point to replacements via supersededBy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<TagStatus<S>>,
    ///When status is 'deprecated', points to the replacement work scope tag record. The record referenced must conform with the lexicon org.hypercerts.workscope.tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub superseded_by: Option<StrongRef<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Category type of this scope.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TagCategory<S: BosStr = DefaultStr> {
    Topic,
    Language,
    Domain,
    Method,
    Other(S),
}

impl<S: BosStr> TagCategory<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Topic => "topic",
            Self::Language => "language",
            Self::Domain => "domain",
            Self::Method => "method",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "topic" => Self::Topic,
            "language" => Self::Language,
            "domain" => Self::Domain,
            "method" => Self::Method,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for TagCategory<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for TagCategory<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for TagCategory<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for TagCategory<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for TagCategory<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for TagCategory<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = TagCategory<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            TagCategory::Topic => TagCategory::Topic,
            TagCategory::Language => TagCategory::Language,
            TagCategory::Domain => TagCategory::Domain,
            TagCategory::Method => TagCategory::Method,
            TagCategory::Other(v) => TagCategory::Other(v.into_static()),
        }
    }
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum TagReferenceDocument<S: BosStr = DefaultStr> {
    #[serde(rename = "org.hypercerts.defs#uri")]
    Uri(Box<Uri<S>>),
    #[serde(rename = "org.hypercerts.defs#smallBlob")]
    SmallBlob(Box<SmallBlob<S>>),
}

/// Lifecycle status of this tag. Communities propose tags, curators accept them, deprecated tags point to replacements via supersededBy.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TagStatus<S: BosStr = DefaultStr> {
    Proposed,
    Accepted,
    Deprecated,
    Other(S),
}

impl<S: BosStr> TagStatus<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Proposed => "proposed",
            Self::Accepted => "accepted",
            Self::Deprecated => "deprecated",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "proposed" => Self::Proposed,
            "accepted" => Self::Accepted,
            "deprecated" => Self::Deprecated,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for TagStatus<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for TagStatus<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for TagStatus<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for TagStatus<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for TagStatus<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for TagStatus<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = TagStatus<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            TagStatus::Proposed => TagStatus::Proposed,
            TagStatus::Accepted => TagStatus::Accepted,
            TagStatus::Deprecated => TagStatus::Deprecated,
            TagStatus::Other(v) => TagStatus::Other(v.into_static()),
        }
    }
}

/// 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 TagGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Tag<S>,
}

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

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

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

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

impl<S: BosStr> Collection for Tag<S> {
    const NSID: &'static str = "org.hypercerts.workscope.tag";
    type Record = TagRecord;
}

impl Collection for TagRecord {
    const NSID: &'static str = "org.hypercerts.workscope.tag";
    type Record = TagRecord;
}

impl<S: BosStr> LexiconSchema for Tag<S> {
    fn nsid() -> &'static str {
        "org.hypercerts.workscope.tag"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_hypercerts_workscope_tag()
    }
    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.category {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("category"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        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()),
                });
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 200usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 200usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.same_as {
            #[allow(unused_comparisons)]
            if value.len() > 20usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("same_as"),
                    max: 20usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.status {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("status"),
                    max: 20usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod 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 Name;
    }
    /// 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 Name = 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 Name = St::Name;
    }
    ///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 Name = St::Name;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type CreatedAt = St::CreatedAt;
        type Key = St::Key;
        type Name = Set<members::name>;
    }
    /// 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 `name` field
        pub struct name(());
    }
}

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

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

impl<S: BosStr> Tag<S> {
    /// Create a new builder for this type
    pub fn builder() -> TagBuilder<tag_state::Empty, S> {
        TagBuilder::builder()
    }
}

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

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

impl<St: tag_state::State, S: BosStr> TagBuilder<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: tag_state::State, S: BosStr> TagBuilder<St, S> {
    /// Set the `category` field (optional)
    pub fn category(mut self, value: impl Into<Option<TagCategory<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `category` field to an Option value (optional)
    pub fn maybe_category(mut self, value: Option<TagCategory<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

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

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

impl<St, S: BosStr> TagBuilder<St, S>
where
    St: tag_state::State,
    St::Name: tag_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(mut self, value: impl Into<S>) -> TagBuilder<tag_state::SetName<St>, S> {
        self._fields.5 = Option::Some(value.into());
        TagBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: tag_state::State, S: BosStr> TagBuilder<St, S> {
    /// Set the `parent` field (optional)
    pub fn parent(mut self, value: impl Into<Option<StrongRef<S>>>) -> Self {
        self._fields.6 = 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.6 = value;
        self
    }
}

impl<St: tag_state::State, S: BosStr> TagBuilder<St, S> {
    /// Set the `referenceDocument` field (optional)
    pub fn reference_document(
        mut self,
        value: impl Into<Option<TagReferenceDocument<S>>>,
    ) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `referenceDocument` field to an Option value (optional)
    pub fn maybe_reference_document(
        mut self,
        value: Option<TagReferenceDocument<S>>,
    ) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St: tag_state::State, S: BosStr> TagBuilder<St, S> {
    /// Set the `sameAs` field (optional)
    pub fn same_as(mut self, value: impl Into<Option<Vec<UriValue<S>>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `sameAs` field to an Option value (optional)
    pub fn maybe_same_as(mut self, value: Option<Vec<UriValue<S>>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<St: tag_state::State, S: BosStr> TagBuilder<St, S> {
    /// Set the `status` field (optional)
    pub fn status(mut self, value: impl Into<Option<TagStatus<S>>>) -> Self {
        self._fields.9 = value.into();
        self
    }
    /// Set the `status` field to an Option value (optional)
    pub fn maybe_status(mut self, value: Option<TagStatus<S>>) -> Self {
        self._fields.9 = value;
        self
    }
}

impl<St: tag_state::State, S: BosStr> TagBuilder<St, S> {
    /// Set the `supersededBy` field (optional)
    pub fn superseded_by(mut self, value: impl Into<Option<StrongRef<S>>>) -> Self {
        self._fields.10 = value.into();
        self
    }
    /// Set the `supersededBy` field to an Option value (optional)
    pub fn maybe_superseded_by(mut self, value: Option<StrongRef<S>>) -> Self {
        self._fields.10 = value;
        self
    }
}

impl<St, S: BosStr> TagBuilder<St, S>
where
    St: tag_state::State,
    St::CreatedAt: tag_state::IsSet,
    St::Key: tag_state::IsSet,
    St::Name: tag_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Tag<S> {
        Tag {
            aliases: self._fields.0,
            category: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            key: self._fields.4.unwrap(),
            name: self._fields.5.unwrap(),
            parent: self._fields.6,
            reference_document: self._fields.7,
            same_as: self._fields.8,
            status: self._fields.9,
            superseded_by: self._fields.10,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Tag<S> {
        Tag {
            aliases: self._fields.0,
            category: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            key: self._fields.4.unwrap(),
            name: self._fields.5.unwrap(),
            parent: self._fields.6,
            reference_document: self._fields.7,
            same_as: self._fields.8,
            status: self._fields.9,
            superseded_by: self._fields.10,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_hypercerts_workscope_tag() -> 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.workscope.tag"),
        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. Tags are composed into structured expressions via CEL (Common Expression Language) on activity records.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("key"), SmolStr::new_static("name"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("aliases"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Alternative human-readable names for this scope (e.g., translations, abbreviations, or common synonyms). Unlike sameAs, these are plain-text labels, not links to external ontologies.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(200usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("category"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Category type of this scope."),
                                    ),
                                    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("key"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Lowercase, underscore-separated machine-readable key for this scope (e.g., 'mangrove_restoration', 'biodiversity_monitoring'). Used as the canonical identifier in CEL expressions.",
                                        ),
                                    ),
                                    max_length: Some(120usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Human-readable name 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.insert(
                                SmolStr::new_static("referenceDocument"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "Link to a governance or reference document where this work scope tag is defined and further explained.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("org.hypercerts.defs#uri"),
                                        CowStr::new_static("org.hypercerts.defs#smallBlob")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("sameAs"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "URIs to semantically equivalent concepts in external ontologies or taxonomies (e.g., Wikidata QIDs, ENVO terms, SDG targets). Used for interoperability, not as documentation.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Uri),
                                        max_length: Some(2048usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(20usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("status"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Lifecycle status of this tag. Communities propose tags, curators accept them, deprecated tags point to replacements via supersededBy.",
                                        ),
                                    ),
                                    max_length: Some(20usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("supersededBy"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}