// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: at.margin.annotation
//
// 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::label::SelfLabels;
use crate::at_margin::annotation;
/// Annotation body - the content of the annotation

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Body<S: BosStr = DefaultStr> {
    ///MIME type of the body content  Defaults to `"text/plain"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_body_format")]
    pub format: Option<S>,
    ///BCP47 language tag
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<S>,
    ///Reference to external body content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri: Option<UriValue<S>>,
    ///Text content of the annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// W3C CssSelector - select DOM elements by CSS selector

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CssSelector<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<S>,
    ///CSS selector string
    pub value: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// W3C FragmentSelector - select by URI fragment

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct FragmentSelector<S: BosStr = DefaultStr> {
    ///Specification the fragment conforms to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conforms_to: Option<UriValue<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<S>,
    ///Fragment identifier value
    pub value: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// The client/agent that created this record

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Generator<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub homepage: Option<UriValue<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<UriValue<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A W3C-compliant web annotation stored on the AT Protocol

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "at.margin.annotation",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Annotation<S: BosStr = DefaultStr> {
    ///The annotation content (text or reference)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<annotation::Body<S>>,
    pub created_at: Datetime,
    ///The client/agent that created this record
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generator: Option<annotation::Generator<S>>,
    ///Self-applied content labels for this annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub labels: Option<SelfLabels<S>>,
    ///W3C motivation for the annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub motivation: Option<AnnotationMotivation<S>>,
    ///License URI (e.g., https://creativecommons.org/licenses/by/4.0/)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rights: Option<UriValue<S>>,
    ///Tags for categorization
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<S>>,
    ///The resource being annotated with optional selector
    pub target: annotation::Target<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// W3C motivation for the annotation

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AnnotationMotivation<S: BosStr = DefaultStr> {
    Commenting,
    Highlighting,
    Bookmarking,
    Tagging,
    Describing,
    Linking,
    Replying,
    Editing,
    Questioning,
    Assessing,
    Other(S),
}

impl<S: BosStr> AnnotationMotivation<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Commenting => "commenting",
            Self::Highlighting => "highlighting",
            Self::Bookmarking => "bookmarking",
            Self::Tagging => "tagging",
            Self::Describing => "describing",
            Self::Linking => "linking",
            Self::Replying => "replying",
            Self::Editing => "editing",
            Self::Questioning => "questioning",
            Self::Assessing => "assessing",
            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() {
            "commenting" => Self::Commenting,
            "highlighting" => Self::Highlighting,
            "bookmarking" => Self::Bookmarking,
            "tagging" => Self::Tagging,
            "describing" => Self::Describing,
            "linking" => Self::Linking,
            "replying" => Self::Replying,
            "editing" => Self::Editing,
            "questioning" => Self::Questioning,
            "assessing" => Self::Assessing,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for AnnotationMotivation<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 AnnotationMotivation<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 AnnotationMotivation<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for AnnotationMotivation<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = AnnotationMotivation<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            AnnotationMotivation::Commenting => AnnotationMotivation::Commenting,
            AnnotationMotivation::Highlighting => AnnotationMotivation::Highlighting,
            AnnotationMotivation::Bookmarking => AnnotationMotivation::Bookmarking,
            AnnotationMotivation::Tagging => AnnotationMotivation::Tagging,
            AnnotationMotivation::Describing => AnnotationMotivation::Describing,
            AnnotationMotivation::Linking => AnnotationMotivation::Linking,
            AnnotationMotivation::Replying => AnnotationMotivation::Replying,
            AnnotationMotivation::Editing => AnnotationMotivation::Editing,
            AnnotationMotivation::Questioning => AnnotationMotivation::Questioning,
            AnnotationMotivation::Assessing => AnnotationMotivation::Assessing,
            AnnotationMotivation::Other(v) => {
                AnnotationMotivation::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 AnnotationGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Annotation<S>,
}

/// W3C RangeSelector - select range between two selectors

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct RangeSelector<S: BosStr = DefaultStr> {
    ///Selector for range end
    pub end_selector: RangeSelectorEndSelector<S>,
    ///Selector for range start
    pub start_selector: RangeSelectorStartSelector<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<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 RangeSelectorEndSelector<S: BosStr = DefaultStr> {
    #[serde(rename = "at.margin.annotation#textQuoteSelector")]
    TextQuoteSelector(Box<annotation::TextQuoteSelector<S>>),
    #[serde(rename = "at.margin.annotation#textPositionSelector")]
    TextPositionSelector(Box<annotation::TextPositionSelector<S>>),
    #[serde(rename = "at.margin.annotation#cssSelector")]
    CssSelector(Box<annotation::CssSelector<S>>),
    #[serde(rename = "at.margin.annotation#xpathSelector")]
    XpathSelector(Box<annotation::XpathSelector<S>>),
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum RangeSelectorStartSelector<S: BosStr = DefaultStr> {
    #[serde(rename = "at.margin.annotation#textQuoteSelector")]
    TextQuoteSelector(Box<annotation::TextQuoteSelector<S>>),
    #[serde(rename = "at.margin.annotation#textPositionSelector")]
    TextPositionSelector(Box<annotation::TextPositionSelector<S>>),
    #[serde(rename = "at.margin.annotation#cssSelector")]
    CssSelector(Box<annotation::CssSelector<S>>),
    #[serde(rename = "at.margin.annotation#xpathSelector")]
    XpathSelector(Box<annotation::XpathSelector<S>>),
}

/// W3C SpecificResource - the target with optional selector

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Target<S: BosStr = DefaultStr> {
    ///Selector to identify the specific segment
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector: Option<TargetSelector<S>>,
    ///The URL being annotated
    pub source: UriValue<S>,
    ///SHA256 hash of normalized URL for indexing
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_hash: Option<S>,
    ///State of the resource at annotation time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<annotation::TimeState<S>>,
    ///Page title at time of annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<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 TargetSelector<S: BosStr = DefaultStr> {
    #[serde(rename = "at.margin.annotation#textQuoteSelector")]
    TextQuoteSelector(Box<annotation::TextQuoteSelector<S>>),
    #[serde(rename = "at.margin.annotation#textPositionSelector")]
    TextPositionSelector(Box<annotation::TextPositionSelector<S>>),
    #[serde(rename = "at.margin.annotation#cssSelector")]
    CssSelector(Box<annotation::CssSelector<S>>),
    #[serde(rename = "at.margin.annotation#xpathSelector")]
    XpathSelector(Box<annotation::XpathSelector<S>>),
    #[serde(rename = "at.margin.annotation#fragmentSelector")]
    FragmentSelector(Box<annotation::FragmentSelector<S>>),
    #[serde(rename = "at.margin.annotation#rangeSelector")]
    RangeSelector(Box<annotation::RangeSelector<S>>),
}

/// W3C TextPositionSelector - select by character offsets

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct TextPositionSelector<S: BosStr = DefaultStr> {
    ///Ending character position (exclusive)
    pub end: i64,
    ///Starting character position (0-indexed, inclusive)
    pub start: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// W3C TextQuoteSelector - select text by quoting it with context

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct TextQuoteSelector<S: BosStr = DefaultStr> {
    ///The exact text to match
    pub exact: S,
    ///Text immediately before the selection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<S>,
    ///Text immediately after the selection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// W3C TimeState - record when content was captured

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct TimeState<S: BosStr = DefaultStr> {
    ///URL to cached/archived version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cached: Option<UriValue<S>>,
    ///When the source was accessed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_date: Option<Datetime>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// W3C XPathSelector - select by XPath expression

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct XpathSelector<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<S>,
    ///XPath expression
    pub value: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

impl<S: BosStr> LexiconSchema for Body<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "body"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.value {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("value"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.value {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 3000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("value"),
                        max: 3000usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for CssSelector<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "cssSelector"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.value;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("value"),
                    max: 2000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for FragmentSelector<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "fragmentSelector"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.value;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("value"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Generator<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "generator"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct AnnotationRecord;
impl XrpcResp for AnnotationRecord {
    const NSID: &'static str = "at.margin.annotation";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = AnnotationGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Annotation<S> {
    const NSID: &'static str = "at.margin.annotation";
    type Record = AnnotationRecord;
}

impl Collection for AnnotationRecord {
    const NSID: &'static str = "at.margin.annotation";
    type Record = AnnotationRecord;
}

impl<S: BosStr> LexiconSchema for Annotation<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.tags {
            #[allow(unused_comparisons)]
            if value.len() > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("tags"),
                    max: 10usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for RangeSelector<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "rangeSelector"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Target<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "target"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.title {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for TextPositionSelector<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "textPositionSelector"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.end;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("end"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.start;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("start"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for TextQuoteSelector<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "textQuoteSelector"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.exact;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 5000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("exact"),
                    max: 5000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.exact;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 1500usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("exact"),
                        max: 1500usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.prefix {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("prefix"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.prefix {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 150usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("prefix"),
                        max: 150usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.suffix {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("suffix"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.suffix {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 150usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("suffix"),
                        max: 150usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for TimeState<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "timeState"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for XpathSelector<S> {
    fn nsid() -> &'static str {
        "at.margin.annotation"
    }
    fn def_name() -> &'static str {
        "xpathSelector"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_margin_annotation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.value;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("value"),
                    max: 2000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

fn _default_body_format<S: FromStaticStr>() -> ::core::option::Option<S> {
    Some(S::from_static("text/plain"))
}

impl Default for Body {
    fn default() -> Self {
        Self {
            format: Some(SmolStr::from("text/plain")),
            language: None,
            uri: None,
            value: None,
            extra_data: Default::default(),
        }
    }
}

fn lexicon_doc_at_margin_annotation() -> 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("at.margin.annotation"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("body"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Annotation body - the content of the annotation",
                        ),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("format"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("MIME type of the body content"),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("language"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("BCP47 language tag")),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("uri"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Reference to external body content"),
                                ),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Text content of the annotation"),
                                ),
                                max_length: Some(10000usize),
                                max_graphemes: Some(3000usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("cssSelector"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C CssSelector - select DOM elements by CSS selector",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("value")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("CSS selector string"),
                                ),
                                max_length: Some(2000usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("fragmentSelector"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C FragmentSelector - select by URI fragment",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("value")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("conformsTo"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Specification the fragment conforms to"),
                                ),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Fragment identifier value"),
                                ),
                                max_length: Some(1000usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("generator"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("The client/agent that created this record"),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("homepage"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("id"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A W3C-compliant web annotation stored on the AT Protocol",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("target"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("body"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#body"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("generator"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#generator"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("labels"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "com.atproto.label.defs#selfLabels",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("motivation"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("W3C motivation for the annotation"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("rights"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "License URI (e.g., https://creativecommons.org/licenses/by/4.0/)",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Uri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Tags for categorization"),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(64usize),
                                        max_graphemes: Some(32usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("target"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#target"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("rangeSelector"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C RangeSelector - select range between two selectors",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("startSelector"),
                            SmolStr::new_static("endSelector")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("endSelector"),
                            LexObjectProperty::Union(LexRefUnion {
                                description: Some(
                                    CowStr::new_static("Selector for range end"),
                                ),
                                refs: vec![
                                    CowStr::new_static("#textQuoteSelector"),
                                    CowStr::new_static("#textPositionSelector"),
                                    CowStr::new_static("#cssSelector"),
                                    CowStr::new_static("#xpathSelector")
                                ],
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("startSelector"),
                            LexObjectProperty::Union(LexRefUnion {
                                description: Some(
                                    CowStr::new_static("Selector for range start"),
                                ),
                                refs: vec![
                                    CowStr::new_static("#textQuoteSelector"),
                                    CowStr::new_static("#textPositionSelector"),
                                    CowStr::new_static("#cssSelector"),
                                    CowStr::new_static("#xpathSelector")
                                ],
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("target"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C SpecificResource - the target with optional selector",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("source")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("selector"),
                            LexObjectProperty::Union(LexRefUnion {
                                description: Some(
                                    CowStr::new_static(
                                        "Selector to identify the specific segment",
                                    ),
                                ),
                                refs: vec![
                                    CowStr::new_static("#textQuoteSelector"),
                                    CowStr::new_static("#textPositionSelector"),
                                    CowStr::new_static("#cssSelector"),
                                    CowStr::new_static("#xpathSelector"),
                                    CowStr::new_static("#fragmentSelector"),
                                    CowStr::new_static("#rangeSelector")
                                ],
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("source"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The URL being annotated"),
                                ),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("sourceHash"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "SHA256 hash of normalized URL for indexing",
                                    ),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("state"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static("#timeState"),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("title"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Page title at time of annotation"),
                                ),
                                max_length: Some(500usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("textPositionSelector"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C TextPositionSelector - select by character offsets",
                        ),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("start"), SmolStr::new_static("end")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("end"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(0i64),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("start"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(0i64),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("textQuoteSelector"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C TextQuoteSelector - select text by quoting it with context",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("exact")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("exact"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The exact text to match"),
                                ),
                                max_length: Some(5000usize),
                                max_graphemes: Some(1500usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("prefix"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Text immediately before the selection"),
                                ),
                                max_length: Some(500usize),
                                max_graphemes: Some(150usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("suffix"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Text immediately after the selection"),
                                ),
                                max_length: Some(500usize),
                                max_graphemes: Some(150usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("timeState"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C TimeState - record when content was captured",
                        ),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("cached"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("URL to cached/archived version"),
                                ),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("sourceDate"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("When the source was accessed"),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("xpathSelector"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "W3C XPathSelector - select by XPath expression",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("value")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("XPath expression")),
                                max_length: Some(2000usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod annotation_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 Target;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Target = 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 Target = St::Target;
    }
    ///State transition - sets the `target` field to Set
    pub struct SetTarget<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTarget<St> {}
    impl<St: State> State for SetTarget<St> {
        type CreatedAt = St::CreatedAt;
        type Target = Set<members::target>;
    }
    /// 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 `target` field
        pub struct target(());
    }
}

/// Builder for constructing an instance of this type.
pub struct AnnotationBuilder<St: annotation_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<annotation::Body<S>>,
        Option<Datetime>,
        Option<annotation::Generator<S>>,
        Option<SelfLabels<S>>,
        Option<AnnotationMotivation<S>>,
        Option<UriValue<S>>,
        Option<Vec<S>>,
        Option<annotation::Target<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Annotation<S> {
    /// Create a new builder for this type
    pub fn builder() -> AnnotationBuilder<annotation_state::Empty, S> {
        AnnotationBuilder::builder()
    }
}

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

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

impl<St: annotation_state::State, S: BosStr> AnnotationBuilder<St, S> {
    /// Set the `body` field (optional)
    pub fn body(mut self, value: impl Into<Option<annotation::Body<S>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `body` field to an Option value (optional)
    pub fn maybe_body(mut self, value: Option<annotation::Body<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<St: annotation_state::State, S: BosStr> AnnotationBuilder<St, S> {
    /// Set the `generator` field (optional)
    pub fn generator(
        mut self,
        value: impl Into<Option<annotation::Generator<S>>>,
    ) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `generator` field to an Option value (optional)
    pub fn maybe_generator(mut self, value: Option<annotation::Generator<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

impl<St: annotation_state::State, S: BosStr> AnnotationBuilder<St, S> {
    /// Set the `motivation` field (optional)
    pub fn motivation(
        mut self,
        value: impl Into<Option<AnnotationMotivation<S>>>,
    ) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `motivation` field to an Option value (optional)
    pub fn maybe_motivation(mut self, value: Option<AnnotationMotivation<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

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

impl<St, S: BosStr> AnnotationBuilder<St, S>
where
    St: annotation_state::State,
    St::Target: annotation_state::IsUnset,
{
    /// Set the `target` field (required)
    pub fn target(
        mut self,
        value: impl Into<annotation::Target<S>>,
    ) -> AnnotationBuilder<annotation_state::SetTarget<St>, S> {
        self._fields.7 = Option::Some(value.into());
        AnnotationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> AnnotationBuilder<St, S>
where
    St: annotation_state::State,
    St::CreatedAt: annotation_state::IsSet,
    St::Target: annotation_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Annotation<S> {
        Annotation {
            body: self._fields.0,
            created_at: self._fields.1.unwrap(),
            generator: self._fields.2,
            labels: self._fields.3,
            motivation: self._fields.4,
            rights: self._fields.5,
            tags: self._fields.6,
            target: self._fields.7.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Annotation<S> {
        Annotation {
            body: self._fields.0,
            created_at: self._fields.1.unwrap(),
            generator: self._fields.2,
            labels: self._fields.3,
            motivation: self._fields.4,
            rights: self._fields.5,
            tags: self._fields.6,
            target: self._fields.7.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod range_selector_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 EndSelector;
        type StartSelector;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type EndSelector = Unset;
        type StartSelector = Unset;
    }
    ///State transition - sets the `end_selector` field to Set
    pub struct SetEndSelector<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetEndSelector<St> {}
    impl<St: State> State for SetEndSelector<St> {
        type EndSelector = Set<members::end_selector>;
        type StartSelector = St::StartSelector;
    }
    ///State transition - sets the `start_selector` field to Set
    pub struct SetStartSelector<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetStartSelector<St> {}
    impl<St: State> State for SetStartSelector<St> {
        type EndSelector = St::EndSelector;
        type StartSelector = Set<members::start_selector>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `end_selector` field
        pub struct end_selector(());
        ///Marker type for the `start_selector` field
        pub struct start_selector(());
    }
}

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

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

impl<S: BosStr> RangeSelector<S> {
    /// Create a new builder for this type
    pub fn builder() -> RangeSelectorBuilder<range_selector_state::Empty, S> {
        RangeSelectorBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> RangeSelectorBuilder<St, S>
where
    St: range_selector_state::State,
    St::EndSelector: range_selector_state::IsUnset,
{
    /// Set the `endSelector` field (required)
    pub fn end_selector(
        mut self,
        value: impl Into<RangeSelectorEndSelector<S>>,
    ) -> RangeSelectorBuilder<range_selector_state::SetEndSelector<St>, S> {
        self._fields.0 = Option::Some(value.into());
        RangeSelectorBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RangeSelectorBuilder<St, S>
where
    St: range_selector_state::State,
    St::StartSelector: range_selector_state::IsUnset,
{
    /// Set the `startSelector` field (required)
    pub fn start_selector(
        mut self,
        value: impl Into<RangeSelectorStartSelector<S>>,
    ) -> RangeSelectorBuilder<range_selector_state::SetStartSelector<St>, S> {
        self._fields.1 = Option::Some(value.into());
        RangeSelectorBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: range_selector_state::State, S: BosStr> RangeSelectorBuilder<St, S> {
    /// Set the `type` field (optional)
    pub fn r#type(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `type` field to an Option value (optional)
    pub fn maybe_type(mut self, value: Option<S>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> RangeSelectorBuilder<St, S>
where
    St: range_selector_state::State,
    St::EndSelector: range_selector_state::IsSet,
    St::StartSelector: range_selector_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> RangeSelector<S> {
        RangeSelector {
            end_selector: self._fields.0.unwrap(),
            start_selector: self._fields.1.unwrap(),
            r#type: self._fields.2,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> RangeSelector<S> {
        RangeSelector {
            end_selector: self._fields.0.unwrap(),
            start_selector: self._fields.1.unwrap(),
            r#type: self._fields.2,
            extra_data: Some(extra_data),
        }
    }
}

pub mod target_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 Source;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Source = Unset;
    }
    ///State transition - sets the `source` field to Set
    pub struct SetSource<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSource<St> {}
    impl<St: State> State for SetSource<St> {
        type Source = Set<members::source>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `source` field
        pub struct source(());
    }
}

/// Builder for constructing an instance of this type.
pub struct TargetBuilder<St: target_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<TargetSelector<S>>,
        Option<UriValue<S>>,
        Option<S>,
        Option<annotation::TimeState<S>>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Target<S> {
    /// Create a new builder for this type
    pub fn builder() -> TargetBuilder<target_state::Empty, S> {
        TargetBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> TargetBuilder<St, S>
where
    St: target_state::State,
    St::Source: target_state::IsUnset,
{
    /// Set the `source` field (required)
    pub fn source(
        mut self,
        value: impl Into<UriValue<S>>,
    ) -> TargetBuilder<target_state::SetSource<St>, S> {
        self._fields.1 = Option::Some(value.into());
        TargetBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St: target_state::State, S: BosStr> TargetBuilder<St, S> {
    /// Set the `state` field (optional)
    pub fn state(mut self, value: impl Into<Option<annotation::TimeState<S>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `state` field to an Option value (optional)
    pub fn maybe_state(mut self, value: Option<annotation::TimeState<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: target_state::State, S: BosStr> TargetBuilder<St, S> {
    /// Set the `title` field (optional)
    pub fn title(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `title` field to an Option value (optional)
    pub fn maybe_title(mut self, value: Option<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> TargetBuilder<St, S>
where
    St: target_state::State,
    St::Source: target_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Target<S> {
        Target {
            selector: self._fields.0,
            source: self._fields.1.unwrap(),
            source_hash: self._fields.2,
            state: self._fields.3,
            title: self._fields.4,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Target<S> {
        Target {
            selector: self._fields.0,
            source: self._fields.1.unwrap(),
            source_hash: self._fields.2,
            state: self._fields.3,
            title: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}

pub mod text_position_selector_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 End;
        type Start;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type End = Unset;
        type Start = Unset;
    }
    ///State transition - sets the `end` field to Set
    pub struct SetEnd<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetEnd<St> {}
    impl<St: State> State for SetEnd<St> {
        type End = Set<members::end>;
        type Start = St::Start;
    }
    ///State transition - sets the `start` field to Set
    pub struct SetStart<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetStart<St> {}
    impl<St: State> State for SetStart<St> {
        type End = St::End;
        type Start = Set<members::start>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `end` field
        pub struct end(());
        ///Marker type for the `start` field
        pub struct start(());
    }
}

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

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

impl<S: BosStr> TextPositionSelector<S> {
    /// Create a new builder for this type
    pub fn builder() -> TextPositionSelectorBuilder<
        text_position_selector_state::Empty,
        S,
    > {
        TextPositionSelectorBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> TextPositionSelectorBuilder<St, S>
where
    St: text_position_selector_state::State,
    St::End: text_position_selector_state::IsUnset,
{
    /// Set the `end` field (required)
    pub fn end(
        mut self,
        value: impl Into<i64>,
    ) -> TextPositionSelectorBuilder<text_position_selector_state::SetEnd<St>, S> {
        self._fields.0 = Option::Some(value.into());
        TextPositionSelectorBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> TextPositionSelectorBuilder<St, S>
where
    St: text_position_selector_state::State,
    St::Start: text_position_selector_state::IsUnset,
{
    /// Set the `start` field (required)
    pub fn start(
        mut self,
        value: impl Into<i64>,
    ) -> TextPositionSelectorBuilder<text_position_selector_state::SetStart<St>, S> {
        self._fields.1 = Option::Some(value.into());
        TextPositionSelectorBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<
    St: text_position_selector_state::State,
    S: BosStr,
> TextPositionSelectorBuilder<St, S> {
    /// Set the `type` field (optional)
    pub fn r#type(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `type` field to an Option value (optional)
    pub fn maybe_type(mut self, value: Option<S>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> TextPositionSelectorBuilder<St, S>
where
    St: text_position_selector_state::State,
    St::End: text_position_selector_state::IsSet,
    St::Start: text_position_selector_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> TextPositionSelector<S> {
        TextPositionSelector {
            end: self._fields.0.unwrap(),
            start: self._fields.1.unwrap(),
            r#type: self._fields.2,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> TextPositionSelector<S> {
        TextPositionSelector {
            end: self._fields.0.unwrap(),
            start: self._fields.1.unwrap(),
            r#type: self._fields.2,
            extra_data: Some(extra_data),
        }
    }
}