// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: art.cllctv.feed.post
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::{CowStr, BosStr, DefaultStr, FromStaticStr};

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::deps::smol_str::SmolStr;
use jacquard_common::types::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::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon, open_union};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::art_cllctv::content::markdoc::Markdoc;
use crate::art_cllctv::content::plaintext::Plaintext;
use crate::art_cllctv::embed::Tombstone;
use crate::art_cllctv::embed::external::External;
use crate::art_cllctv::embed::external_video::ExternalVideo;
use crate::art_cllctv::embed::images::Images;
use crate::com_atproto::label::SelfLabels;
use crate::art_cllctv::feed::post;

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

/// Record containing a cllctv.ART post.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "art.cllctv.feed.post",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Post<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<post::Category<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<PostContent<S>>,
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embed: Option<PostEmbed<S>>,
    ///Self-label values for this post. Effectively content warnings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub labels: Option<SelfLabels<S>>,
    ///Indicates human language of post primary text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub langs: Option<Vec<Language>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub og_image: Option<BlobRef<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published_at: Option<Datetime>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tombstone: Option<Tombstone<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum PostContent<S: BosStr = DefaultStr> {
    #[serde(rename = "art.cllctv.content.plaintext")]
    Plaintext(Box<Plaintext<S>>),
    #[serde(rename = "art.cllctv.content.markdoc")]
    Markdoc(Box<Markdoc<S>>),
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum PostEmbed<S: BosStr = DefaultStr> {
    #[serde(rename = "art.cllctv.embed.images")]
    Images(Box<Images<S>>),
    #[serde(rename = "art.cllctv.embed.external")]
    External(Box<External<S>>),
    #[serde(rename = "art.cllctv.embed.externalVideo")]
    ExternalVideo(Box<ExternalVideo<S>>),
}

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

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

impl<S: BosStr> LexiconSchema for Category<S> {
    fn nsid() -> &'static str {
        "art.cllctv.feed.post"
    }
    fn def_name() -> &'static str {
        "category"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_art_cllctv_feed_post()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct PostRecord;
impl XrpcResp for PostRecord {
    const NSID: &'static str = "art.cllctv.feed.post";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = PostGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Post<S> {
    const NSID: &'static str = "art.cllctv.feed.post";
    type Record = PostRecord;
}

impl Collection for PostRecord {
    const NSID: &'static str = "art.cllctv.feed.post";
    type Record = PostRecord;
}

impl<S: BosStr> LexiconSchema for Post<S> {
    fn nsid() -> &'static str {
        "art.cllctv.feed.post"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_art_cllctv_feed_post()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 3000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 3000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 300usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 300usize,
                        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.og_image {
            {
                let size = value.blob().size;
                if size > 5000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("og_image"),
                        max: 5000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.og_image {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/png"];
                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("og_image"),
                        accepted: vec!["image/png".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        if let Some(ref value) = self.title {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1280usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 1280usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.title {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 128usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("title"),
                        max: 128usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

fn lexicon_doc_art_cllctv_feed_post() -> 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("art.cllctv.feed.post"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("category"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("group")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("group"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("labels"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::String(LexString {
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("Record containing a cllctv.ART post."),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("createdAt")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("category"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#category"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::Union(LexRefUnion {
                                    refs: vec![
                                        CowStr::new_static("art.cllctv.content.plaintext"),
                                        CowStr::new_static("art.cllctv.content.markdoc")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(3000usize),
                                    max_graphemes: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("embed"),
                                LexObjectProperty::Union(LexRefUnion {
                                    refs: vec![
                                        CowStr::new_static("art.cllctv.embed.images"),
                                        CowStr::new_static("art.cllctv.embed.external"),
                                        CowStr::new_static("art.cllctv.embed.externalVideo")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("labels"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "Self-label values for this post. Effectively content warnings.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("com.atproto.label.defs#selfLabels")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("langs"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Indicates human language of post primary text content.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::Language),
                                        ..Default::default()
                                    }),
                                    max_length: Some(3usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("ogImage"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("publishedAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(1280usize),
                                    max_graphemes: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tombstone"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "art.cllctv.embed.defs#tombstone",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

/// Builder for constructing an instance of this type.
pub struct PostBuilder<St: post_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<post::Category<S>>,
        Option<PostContent<S>>,
        Option<Datetime>,
        Option<S>,
        Option<PostEmbed<S>>,
        Option<SelfLabels<S>>,
        Option<Vec<Language>>,
        Option<BlobRef<S>>,
        Option<Datetime>,
        Option<S>,
        Option<Tombstone<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Post<S> {
    /// Create a new builder for this type
    pub fn builder() -> PostBuilder<post_state::Empty, S> {
        PostBuilder::builder()
    }
}

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

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

impl<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `category` field (optional)
    pub fn category(mut self, value: impl Into<Option<post::Category<S>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `category` field to an Option value (optional)
    pub fn maybe_category(mut self, value: Option<post::Category<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `content` field (optional)
    pub fn content(mut self, value: impl Into<Option<PostContent<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `content` field to an Option value (optional)
    pub fn maybe_content(mut self, value: Option<PostContent<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

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

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

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

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

impl<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `ogImage` field (optional)
    pub fn og_image(mut self, value: impl Into<Option<BlobRef<S>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `ogImage` field to an Option value (optional)
    pub fn maybe_og_image(mut self, value: Option<BlobRef<S>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `publishedAt` field (optional)
    pub fn published_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `publishedAt` field to an Option value (optional)
    pub fn maybe_published_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.8 = value;
        self
    }
}

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

impl<St: post_state::State, S: BosStr> PostBuilder<St, S> {
    /// Set the `tombstone` field (optional)
    pub fn tombstone(mut self, value: impl Into<Option<Tombstone<S>>>) -> Self {
        self._fields.10 = value.into();
        self
    }
    /// Set the `tombstone` field to an Option value (optional)
    pub fn maybe_tombstone(mut self, value: Option<Tombstone<S>>) -> Self {
        self._fields.10 = value;
        self
    }
}

impl<St, S: BosStr> PostBuilder<St, S>
where
    St: post_state::State,
    St::CreatedAt: post_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Post<S> {
        Post {
            category: self._fields.0,
            content: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            embed: self._fields.4,
            labels: self._fields.5,
            langs: self._fields.6,
            og_image: self._fields.7,
            published_at: self._fields.8,
            title: self._fields.9,
            tombstone: self._fields.10,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Post<S> {
        Post {
            category: self._fields.0,
            content: self._fields.1,
            created_at: self._fields.2.unwrap(),
            description: self._fields.3,
            embed: self._fields.4,
            labels: self._fields.5,
            langs: self._fields.6,
            og_image: self._fields.7,
            published_at: self._fields.8,
            title: self._fields.9,
            tombstone: self._fields.10,
            extra_data: Some(extra_data),
        }
    }
}