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

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Tag<'a> {
    ///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")]
    #[serde(borrow)]
    pub aliases: Option<Vec<CowStr<'a>>>,
    ///Category type of this scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub category: Option<TagCategory<'a>>,
    ///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")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///Lowercase, underscore-separated machine-readable key for this scope (e.g., 'mangrove_restoration', 'biodiversity_monitoring'). Used as the canonical identifier in CEL expressions.
    #[serde(borrow)]
    pub key: CowStr<'a>,
    ///Human-readable name for this scope.
    #[serde(borrow)]
    pub name: CowStr<'a>,
    ///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")]
    #[serde(borrow)]
    pub parent: Option<StrongRef<'a>>,
    ///Link to a governance or reference document where this work scope tag is defined and further explained.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub reference_document: Option<TagReferenceDocument<'a>>,
    ///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")]
    #[serde(borrow)]
    pub same_as: Option<Vec<UriValue<'a>>>,
    ///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")]
    #[serde(borrow)]
    pub status: Option<TagStatus<'a>>,
    ///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")]
    #[serde(borrow)]
    pub superseded_by: Option<StrongRef<'a>>,
}

/// Category type of this scope.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TagCategory<'a> {
    Topic,
    Language,
    Domain,
    Method,
    Other(CowStr<'a>),
}

impl<'a> TagCategory<'a> {
    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(),
        }
    }
}

impl<'a> From<&'a str> for TagCategory<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "topic" => Self::Topic,
            "language" => Self::Language,
            "domain" => Self::Domain,
            "method" => Self::Method,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for TagCategory<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "topic" => Self::Topic,
            "language" => Self::Language,
            "domain" => Self::Domain,
            "method" => Self::Method,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for TagCategory<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for TagCategory<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for TagCategory<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for TagCategory<'_> {
    type Output = TagCategory<'static>;
    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")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum TagReferenceDocument<'a> {
    #[serde(rename = "org.hypercerts.defs#uri")]
    Uri(Box<Uri<'a>>),
    #[serde(rename = "org.hypercerts.defs#smallBlob")]
    SmallBlob(Box<SmallBlob<'a>>),
}

/// 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<'a> {
    Proposed,
    Accepted,
    Deprecated,
    Other(CowStr<'a>),
}

impl<'a> TagStatus<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Proposed => "proposed",
            Self::Accepted => "accepted",
            Self::Deprecated => "deprecated",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for TagStatus<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "proposed" => Self::Proposed,
            "accepted" => Self::Accepted,
            "deprecated" => Self::Deprecated,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for TagStatus<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "proposed" => Self::Proposed,
            "accepted" => Self::Accepted,
            "deprecated" => Self::Deprecated,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for TagStatus<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for TagStatus<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for TagStatus<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for TagStatus<'_> {
    type Output = TagStatus<'static>;
    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<'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: Tag<'a>,
}

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

/// 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<'de> = TagGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Tag<'_> {
    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<'a> LexiconSchema for Tag<'a> {
    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 Name;
        type CreatedAt;
        type Key;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Name = Unset;
        type CreatedAt = Unset;
        type Key = Unset;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetName<S> {}
    impl<S: State> State for SetName<S> {
        type Name = Set<members::name>;
        type CreatedAt = S::CreatedAt;
        type Key = S::Key;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type Name = S::Name;
        type CreatedAt = Set<members::created_at>;
        type Key = S::Key;
    }
    ///State transition - sets the `key` field to Set
    pub struct SetKey<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetKey<S> {}
    impl<S: State> State for SetKey<S> {
        type Name = S::Name;
        type CreatedAt = S::CreatedAt;
        type Key = Set<members::key>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `key` field
        pub struct key(());
    }
}

/// Builder for constructing an instance of this type
pub struct TagBuilder<'a, S: tag_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<CowStr<'a>>>,
        Option<TagCategory<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<StrongRef<'a>>,
        Option<TagReferenceDocument<'a>>,
        Option<Vec<UriValue<'a>>>,
        Option<TagStatus<'a>>,
        Option<StrongRef<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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

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

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

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

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

impl<'a, S: tag_state::State> TagBuilder<'a, S> {
    /// Set the `referenceDocument` field (optional)
    pub fn reference_document(
        mut self,
        value: impl Into<Option<TagReferenceDocument<'a>>>,
    ) -> 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<'a>>,
    ) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S: tag_state::State> TagBuilder<'a, S> {
    /// Set the `sameAs` field (optional)
    pub fn same_as(mut self, value: impl Into<Option<Vec<UriValue<'a>>>>) -> 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<'a>>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S: tag_state::State> TagBuilder<'a, S> {
    /// Set the `status` field (optional)
    pub fn status(mut self, value: impl Into<Option<TagStatus<'a>>>) -> 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<'a>>) -> Self {
        self._fields.9 = value;
        self
    }
}

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

impl<'a, S> TagBuilder<'a, S>
where
    S: tag_state::State,
    S::Name: tag_state::IsSet,
    S::CreatedAt: tag_state::IsSet,
    S::Key: tag_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Tag<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Tag<'a> {
        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()
    }
}