// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: systems.timker.hawlt.note
//
// 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::blob::BlobRef;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime, Language};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
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::systems_timker::hawlt::note;
/// An image attachment with alt text.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Attachment<'a> {
    ///Alt text for the image. Required for accessibility.
    #[serde(borrow)]
    pub alt: CowStr<'a>,
    ///The image blob. Max 5MB.
    #[serde(borrow)]
    pub image: BlobRef<'a>,
}

/// Record containing a Hawlt note.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Note<'a> {
    ///Images attached to the note. Max 4 attachments, 5MB each
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub attachments: Option<Vec<note::Attachment<'a>>>,
    /**The primary note content. Max 3000 graphemes, 30000 bytes
Note: large string limit is intentional for diary-style entries.*/
    #[serde(borrow)]
    pub content: CowStr<'a>,
    ///Content warning label. When present, note content should be hidden by default. Max 100 graphemes, 1000 bytes
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub content_warning: Option<CowStr<'a>>,
    ///Client-declared timestamp when this note was originally created.
    pub created_at: Datetime,
    ///Indicates human language of note primary text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub langs: Option<Vec<Language>>,
    ///Array of string used to tags or categorize the note. Avoid prepending with hashtags.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tags: Option<Vec<CowStr<'a>>>,
}

/// 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 NoteGetRecordOutput<'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: Note<'a>,
}

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

impl<'a> LexiconSchema for Attachment<'a> {
    fn nsid() -> &'static str {
        "systems.timker.hawlt.note"
    }
    fn def_name() -> &'static str {
        "attachment"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_systems_timker_hawlt_note()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.alt;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("alt"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.alt;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 1000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("alt"),
                        max: 1000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.image;
            {
                let size = value.blob().size;
                if size > 5000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("image"),
                        max: 5000000usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.image;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/*"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("image"),
                        accepted: vec!["image/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct NoteRecord;
impl XrpcResp for NoteRecord {
    const NSID: &'static str = "systems.timker.hawlt.note";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = NoteGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Note<'_> {
    const NSID: &'static str = "systems.timker.hawlt.note";
    type Record = NoteRecord;
}

impl Collection for NoteRecord {
    const NSID: &'static str = "systems.timker.hawlt.note";
    type Record = NoteRecord;
}

impl<'a> LexiconSchema for Note<'a> {
    fn nsid() -> &'static str {
        "systems.timker.hawlt.note"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_systems_timker_hawlt_note()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.attachments {
            #[allow(unused_comparisons)]
            if value.len() > 4usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("attachments"),
                    max: 4usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.content;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 30000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("content"),
                    max: 30000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.content;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 3000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("content"),
                        max: 3000usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.content_warning {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("content_warning"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.content_warning {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 100usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("content_warning"),
                        max: 100usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.langs {
            #[allow(unused_comparisons)]
            if value.len() > 3usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("langs"),
                    max: 3usize,
                    actual: value.len(),
                });
            }
        }
        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(())
    }
}

pub mod attachment_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 Image;
        type Alt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Image = Unset;
        type Alt = Unset;
    }
    ///State transition - sets the `image` field to Set
    pub struct SetImage<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetImage<S> {}
    impl<S: State> State for SetImage<S> {
        type Image = Set<members::image>;
        type Alt = S::Alt;
    }
    ///State transition - sets the `alt` field to Set
    pub struct SetAlt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAlt<S> {}
    impl<S: State> State for SetAlt<S> {
        type Image = S::Image;
        type Alt = Set<members::alt>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `image` field
        pub struct image(());
        ///Marker type for the `alt` field
        pub struct alt(());
    }
}

/// Builder for constructing an instance of this type
pub struct AttachmentBuilder<'a, S: attachment_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<BlobRef<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Attachment<'a> {
    /// Create a new builder for this type
    pub fn new() -> AttachmentBuilder<'a, attachment_state::Empty> {
        AttachmentBuilder::new()
    }
}

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

impl<'a, S> AttachmentBuilder<'a, S>
where
    S: attachment_state::State,
    S::Alt: attachment_state::IsUnset,
{
    /// Set the `alt` field (required)
    pub fn alt(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> AttachmentBuilder<'a, attachment_state::SetAlt<S>> {
        self._fields.0 = Option::Some(value.into());
        AttachmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AttachmentBuilder<'a, S>
where
    S: attachment_state::State,
    S::Image: attachment_state::IsUnset,
{
    /// Set the `image` field (required)
    pub fn image(
        mut self,
        value: impl Into<BlobRef<'a>>,
    ) -> AttachmentBuilder<'a, attachment_state::SetImage<S>> {
        self._fields.1 = Option::Some(value.into());
        AttachmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> AttachmentBuilder<'a, S>
where
    S: attachment_state::State,
    S::Image: attachment_state::IsSet,
    S::Alt: attachment_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Attachment<'a> {
        Attachment {
            alt: self._fields.0.unwrap(),
            image: self._fields.1.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>,
        >,
    ) -> Attachment<'a> {
        Attachment {
            alt: self._fields.0.unwrap(),
            image: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_systems_timker_hawlt_note() -> 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("systems.timker.hawlt.note"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("attachment"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("An image attachment with alt text."),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("image"), SmolStr::new_static("alt")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("alt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Alt text for the image. Required for accessibility.",
                                    ),
                                ),
                                max_length: Some(10000usize),
                                max_graphemes: Some(1000usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("image"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("Record containing a Hawlt note."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("content"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("attachments"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Images attached to the note. Max 4 attachments, 5MB each",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#attachment"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(4usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The primary note content. Max 3000 graphemes, 30000 bytes\nNote: large string limit is intentional for diary-style entries.",
                                        ),
                                    ),
                                    max_length: Some(30000usize),
                                    max_graphemes: Some(3000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("contentWarning"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Content warning label. When present, note content should be hidden by default. Max 100 graphemes, 1000 bytes",
                                        ),
                                    ),
                                    max_length: Some(1000usize),
                                    max_graphemes: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when this note was originally created.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("langs"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Indicates human language of note primary text content.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Language),
                                        ..Default::default()
                                    }),
                                    max_length: Some(3usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tags"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Array of string used to tags or categorize the note. Avoid prepending with hashtags.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "Tag to categorize the note. Max 128 graphemes, 1280 bytes",
                                            ),
                                        ),
                                        max_length: Some(1280usize),
                                        max_graphemes: Some(128usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

/// Builder for constructing an instance of this type
pub struct NoteBuilder<'a, S: note_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Vec<note::Attachment<'a>>>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<Datetime>,
        Option<Vec<Language>>,
        Option<Vec<CowStr<'a>>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Note<'a> {
    /// Create a new builder for this type
    pub fn new() -> NoteBuilder<'a, note_state::Empty> {
        NoteBuilder::new()
    }
}

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

impl<'a, S: note_state::State> NoteBuilder<'a, S> {
    /// Set the `attachments` field (optional)
    pub fn attachments(
        mut self,
        value: impl Into<Option<Vec<note::Attachment<'a>>>>,
    ) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `attachments` field to an Option value (optional)
    pub fn maybe_attachments(
        mut self,
        value: Option<Vec<note::Attachment<'a>>>,
    ) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S> NoteBuilder<'a, S>
where
    S: note_state::State,
    S::Content: note_state::IsUnset,
{
    /// Set the `content` field (required)
    pub fn content(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> NoteBuilder<'a, note_state::SetContent<S>> {
        self._fields.1 = Option::Some(value.into());
        NoteBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: note_state::State> NoteBuilder<'a, S> {
    /// Set the `contentWarning` field (optional)
    pub fn content_warning(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `contentWarning` field to an Option value (optional)
    pub fn maybe_content_warning(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

impl<'a, S: note_state::State> NoteBuilder<'a, S> {
    /// Set the `langs` field (optional)
    pub fn langs(mut self, value: impl Into<Option<Vec<Language>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `langs` field to an Option value (optional)
    pub fn maybe_langs(mut self, value: Option<Vec<Language>>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

impl<'a, S> NoteBuilder<'a, S>
where
    S: note_state::State,
    S::Content: note_state::IsSet,
    S::CreatedAt: note_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Note<'a> {
        Note {
            attachments: self._fields.0,
            content: self._fields.1.unwrap(),
            content_warning: self._fields.2,
            created_at: self._fields.3.unwrap(),
            langs: self._fields.4,
            tags: self._fields.5,
            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>,
        >,
    ) -> Note<'a> {
        Note {
            attachments: self._fields.0,
            content: self._fields.1.unwrap(),
            content_warning: self._fields.2,
            created_at: self._fields.3.unwrap(),
            langs: self._fields.4,
            tags: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}