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

#[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::label::SelfLabels;
use crate::at_margin::annotation;
/// Annotation body - the content of the annotation

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Body<'a> {
    ///MIME type of the body content  Defaults to `"text/plain"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_body_format")]
    #[serde(borrow)]
    pub format: Option<CowStr<'a>>,
    ///BCP47 language tag
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub language: Option<CowStr<'a>>,
    ///Reference to external body content
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub uri: Option<UriValue<'a>>,
    ///Text content of the annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub value: Option<CowStr<'a>>,
}

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct CssSelector<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#type: Option<CowStr<'a>>,
    ///CSS selector string
    #[serde(borrow)]
    pub value: CowStr<'a>,
}

/// W3C FragmentSelector - select by URI fragment

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct FragmentSelector<'a> {
    ///Specification the fragment conforms to
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub conforms_to: Option<UriValue<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#type: Option<CowStr<'a>>,
    ///Fragment identifier value
    #[serde(borrow)]
    pub value: CowStr<'a>,
}

/// The client/agent that created this record

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct Generator<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub homepage: Option<UriValue<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub id: Option<UriValue<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub name: Option<CowStr<'a>>,
}

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Annotation<'a> {
    ///The annotation content (text or reference)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub body: Option<annotation::Body<'a>>,
    pub created_at: Datetime,
    ///The client/agent that created this record
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub generator: Option<annotation::Generator<'a>>,
    ///Self-applied content labels for this annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub labels: Option<SelfLabels<'a>>,
    ///W3C motivation for the annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub motivation: Option<AnnotationMotivation<'a>>,
    ///License URI (e.g., https://creativecommons.org/licenses/by/4.0/)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub rights: Option<UriValue<'a>>,
    ///Tags for categorization
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
    ///The resource being annotated with optional selector
    #[serde(borrow)]
    pub target: annotation::Target<'a>,
}

/// W3C motivation for the annotation

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AnnotationMotivation<'a> {
    Commenting,
    Highlighting,
    Bookmarking,
    Tagging,
    Describing,
    Linking,
    Replying,
    Editing,
    Questioning,
    Assessing,
    Other(CowStr<'a>),
}

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

impl<'a> From<&'a str> for AnnotationMotivation<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "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(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for AnnotationMotivation<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "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(CowStr::from(s)),
        }
    }
}

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

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

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

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

/// W3C RangeSelector - select range between two selectors

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct RangeSelector<'a> {
    ///Selector for range end
    #[serde(borrow)]
    pub end_selector: RangeSelectorEndSelector<'a>,
    ///Selector for range start
    #[serde(borrow)]
    pub start_selector: RangeSelectorStartSelector<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#type: Option<CowStr<'a>>,
}


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


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

/// W3C SpecificResource - the target with optional selector

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Target<'a> {
    ///Selector to identify the specific segment
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub selector: Option<TargetSelector<'a>>,
    ///The URL being annotated
    #[serde(borrow)]
    pub source: UriValue<'a>,
    ///SHA256 hash of normalized URL for indexing
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub source_hash: Option<CowStr<'a>>,
    ///State of the resource at annotation time
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub state: Option<annotation::TimeState<'a>>,
    ///Page title at time of annotation
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub title: Option<CowStr<'a>>,
}


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

/// W3C TextPositionSelector - select by character offsets

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct TextPositionSelector<'a> {
    ///Ending character position (exclusive)
    pub end: i64,
    ///Starting character position (0-indexed, inclusive)
    pub start: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#type: Option<CowStr<'a>>,
}

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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct TextQuoteSelector<'a> {
    ///The exact text to match
    #[serde(borrow)]
    pub exact: CowStr<'a>,
    ///Text immediately before the selection
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub prefix: Option<CowStr<'a>>,
    ///Text immediately after the selection
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub suffix: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#type: Option<CowStr<'a>>,
}

/// W3C TimeState - record when content was captured

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct TimeState<'a> {
    ///URL to cached/archived version
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cached: Option<UriValue<'a>>,
    ///When the source was accessed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_date: Option<Datetime>,
}

/// W3C XPathSelector - select by XPath expression

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct XpathSelector<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#type: Option<CowStr<'a>>,
    ///XPath expression
    #[serde(borrow)]
    pub value: CowStr<'a>,
}

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

impl<'a> LexiconSchema for Body<'a> {
    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<'a> LexiconSchema for CssSelector<'a> {
    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<'a> LexiconSchema for FragmentSelector<'a> {
    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<'a> LexiconSchema for Generator<'a> {
    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<'de> = AnnotationGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Annotation<'_> {
    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<'a> LexiconSchema for Annotation<'a> {
    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<'a> LexiconSchema for RangeSelector<'a> {
    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<'a> LexiconSchema for Target<'a> {
    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<'a> LexiconSchema for TextPositionSelector<'a> {
    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<'a> LexiconSchema for TextQuoteSelector<'a> {
    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<'a> LexiconSchema for TimeState<'a> {
    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<'a> LexiconSchema for XpathSelector<'a> {
    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() -> Option<CowStr<'static>> {
    Some(CowStr::from("text/plain"))
}

impl Default for Body<'_> {
    fn default() -> Self {
        Self {
            format: Some(CowStr::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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type CreatedAt = Set<members::created_at>;
        type Target = S::Target;
    }
    ///State transition - sets the `target` field to Set
    pub struct SetTarget<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetTarget<S> {}
    impl<S: State> State for SetTarget<S> {
        type CreatedAt = S::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<'a, S: annotation_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<annotation::Body<'a>>,
        Option<Datetime>,
        Option<annotation::Generator<'a>>,
        Option<SelfLabels<'a>>,
        Option<AnnotationMotivation<'a>>,
        Option<UriValue<'a>>,
        Option<Vec<CowStr<'a>>>,
        Option<annotation::Target<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

impl<'a, S: annotation_state::State> AnnotationBuilder<'a, S> {
    /// Set the `body` field (optional)
    pub fn body(mut self, value: impl Into<Option<annotation::Body<'a>>>) -> 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<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

impl<'a, S: annotation_state::State> AnnotationBuilder<'a, S> {
    /// Set the `generator` field (optional)
    pub fn generator(
        mut self,
        value: impl Into<Option<annotation::Generator<'a>>>,
    ) -> 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<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

impl<'a, S: annotation_state::State> AnnotationBuilder<'a, S> {
    /// Set the `motivation` field (optional)
    pub fn motivation(
        mut self,
        value: impl Into<Option<AnnotationMotivation<'a>>>,
    ) -> 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<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: annotation_state::State> AnnotationBuilder<'a, S> {
    /// Set the `rights` field (optional)
    pub fn rights(mut self, value: impl Into<Option<UriValue<'a>>>) -> 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<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

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

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

impl<'a, S> AnnotationBuilder<'a, S>
where
    S: annotation_state::State,
    S::CreatedAt: annotation_state::IsSet,
    S::Target: annotation_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Annotation<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Annotation<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetEndSelector<S> {}
    impl<S: State> State for SetEndSelector<S> {
        type EndSelector = Set<members::end_selector>;
        type StartSelector = S::StartSelector;
    }
    ///State transition - sets the `start_selector` field to Set
    pub struct SetStartSelector<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetStartSelector<S> {}
    impl<S: State> State for SetStartSelector<S> {
        type EndSelector = S::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<'a, S: range_selector_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<RangeSelectorEndSelector<'a>>,
        Option<RangeSelectorStartSelector<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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

impl<'a, S> RangeSelectorBuilder<'a, S>
where
    S: range_selector_state::State,
    S::EndSelector: range_selector_state::IsSet,
    S::StartSelector: range_selector_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> RangeSelector<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> RangeSelector<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSource<S> {}
    impl<S: State> State for SetSource<S> {
        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<'a, S: target_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<TargetSelector<'a>>,
        Option<UriValue<'a>>,
        Option<CowStr<'a>>,
        Option<annotation::TimeState<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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

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

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

impl<'a, S> TargetBuilder<'a, S>
where
    S: target_state::State,
    S::Source: target_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Target<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Target<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetEnd<S> {}
    impl<S: State> State for SetEnd<S> {
        type End = Set<members::end>;
        type Start = S::Start;
    }
    ///State transition - sets the `start` field to Set
    pub struct SetStart<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetStart<S> {}
    impl<S: State> State for SetStart<S> {
        type End = S::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<'a, S: text_position_selector_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<i64>, Option<i64>, Option<CowStr<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

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

impl<'a, S> TextPositionSelectorBuilder<'a, S>
where
    S: text_position_selector_state::State,
    S::End: text_position_selector_state::IsSet,
    S::Start: text_position_selector_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> TextPositionSelector<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> TextPositionSelector<'a> {
        TextPositionSelector {
            end: self._fields.0.unwrap(),
            start: self._fields.1.unwrap(),
            r#type: self._fields.2,
            extra_data: Some(extra_data),
        }
    }
}