// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: computer.aesthetic.tape
//
// 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};
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};

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Tape<'a> {
    ///Permanent link to view on aesthetic.computer (e.g., https://aesthetic.computer/!a3x)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub ac_url: Option<CowStr<'a>>,
    ///Short alphanumeric code for easy lookup (e.g., 'a3x')
    #[serde(borrow)]
    pub code: CowStr<'a>,
    ///MongoDB ObjectId reference for bi-directional sync
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#ref: Option<CowStr<'a>>,
    ///The unique slug identifier for this tape (e.g., wand-1729177200000)
    #[serde(borrow)]
    pub slug: CowStr<'a>,
    ///Thumbnail image from midpoint frame, 3x scaled with nearest neighbor (max 1MB)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub thumbnail: Option<BlobRef<'a>>,
    ///MP4 video with 3x pixel scaling and audio soundtrack (max 50MB)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub video: Option<BlobRef<'a>>,
    ///ISO 8601 timestamp when the tape was created
    pub when: Datetime,
    ///Direct URL to download the original ZIP file with frames and audio
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub zip_url: Option<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 TapeGetRecordOutput<'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: Tape<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct TapeRecord;
impl XrpcResp for TapeRecord {
    const NSID: &'static str = "computer.aesthetic.tape";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = TapeGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Tape<'_> {
    const NSID: &'static str = "computer.aesthetic.tape";
    type Record = TapeRecord;
}

impl Collection for TapeRecord {
    const NSID: &'static str = "computer.aesthetic.tape";
    type Record = TapeRecord;
}

impl<'a> LexiconSchema for Tape<'a> {
    fn nsid() -> &'static str {
        "computer.aesthetic.tape"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_computer_aesthetic_tape()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.thumbnail {
            {
                let size = value.blob().size;
                if size > 1048576usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("thumbnail"),
                        max: 1048576usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.thumbnail {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/jpeg", "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("thumbnail"),
                        accepted: vec![
                            "image/jpeg".to_string(), "image/png".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        if let Some(ref value) = self.video {
            {
                let size = value.blob().size;
                if size > 52428800usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("video"),
                        max: 52428800usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.video {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["video/mp4"];
                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("video"),
                        accepted: vec!["video/mp4".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod tape_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 Slug;
        type Code;
        type When;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Slug = Unset;
        type Code = Unset;
        type When = Unset;
    }
    ///State transition - sets the `slug` field to Set
    pub struct SetSlug<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSlug<S> {}
    impl<S: State> State for SetSlug<S> {
        type Slug = Set<members::slug>;
        type Code = S::Code;
        type When = S::When;
    }
    ///State transition - sets the `code` field to Set
    pub struct SetCode<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCode<S> {}
    impl<S: State> State for SetCode<S> {
        type Slug = S::Slug;
        type Code = Set<members::code>;
        type When = S::When;
    }
    ///State transition - sets the `when` field to Set
    pub struct SetWhen<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetWhen<S> {}
    impl<S: State> State for SetWhen<S> {
        type Slug = S::Slug;
        type Code = S::Code;
        type When = Set<members::when>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `slug` field
        pub struct slug(());
        ///Marker type for the `code` field
        pub struct code(());
        ///Marker type for the `when` field
        pub struct when(());
    }
}

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

impl<'a> Tape<'a> {
    /// Create a new builder for this type
    pub fn new() -> TapeBuilder<'a, tape_state::Empty> {
        TapeBuilder::new()
    }
}

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

impl<'a, S: tape_state::State> TapeBuilder<'a, S> {
    /// Set the `acUrl` field (optional)
    pub fn ac_url(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `acUrl` field to an Option value (optional)
    pub fn maybe_ac_url(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

impl<'a, S> TapeBuilder<'a, S>
where
    S: tape_state::State,
    S::Slug: tape_state::IsUnset,
{
    /// Set the `slug` field (required)
    pub fn slug(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> TapeBuilder<'a, tape_state::SetSlug<S>> {
        self._fields.3 = Option::Some(value.into());
        TapeBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: tape_state::State> TapeBuilder<'a, S> {
    /// Set the `thumbnail` field (optional)
    pub fn thumbnail(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `thumbnail` field to an Option value (optional)
    pub fn maybe_thumbnail(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S: tape_state::State> TapeBuilder<'a, S> {
    /// Set the `video` field (optional)
    pub fn video(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `video` field to an Option value (optional)
    pub fn maybe_video(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> TapeBuilder<'a, S>
where
    S: tape_state::State,
    S::When: tape_state::IsUnset,
{
    /// Set the `when` field (required)
    pub fn when(
        mut self,
        value: impl Into<Datetime>,
    ) -> TapeBuilder<'a, tape_state::SetWhen<S>> {
        self._fields.6 = Option::Some(value.into());
        TapeBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: tape_state::State> TapeBuilder<'a, S> {
    /// Set the `zipUrl` field (optional)
    pub fn zip_url(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `zipUrl` field to an Option value (optional)
    pub fn maybe_zip_url(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<'a, S> TapeBuilder<'a, S>
where
    S: tape_state::State,
    S::Slug: tape_state::IsSet,
    S::Code: tape_state::IsSet,
    S::When: tape_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Tape<'a> {
        Tape {
            ac_url: self._fields.0,
            code: self._fields.1.unwrap(),
            r#ref: self._fields.2,
            slug: self._fields.3.unwrap(),
            thumbnail: self._fields.4,
            video: self._fields.5,
            when: self._fields.6.unwrap(),
            zip_url: self._fields.7,
            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>,
        >,
    ) -> Tape<'a> {
        Tape {
            ac_url: self._fields.0,
            code: self._fields.1.unwrap(),
            r#ref: self._fields.2,
            slug: self._fields.3.unwrap(),
            thumbnail: self._fields.4,
            video: self._fields.5,
            when: self._fields.6.unwrap(),
            zip_url: self._fields.7,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_computer_aesthetic_tape() -> 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("computer.aesthetic.tape"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("slug"), SmolStr::new_static("code"),
                                SmolStr::new_static("when")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("acUrl"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Permanent link to view on aesthetic.computer (e.g., https://aesthetic.computer/!a3x)",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("code"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Short alphanumeric code for easy lookup (e.g., 'a3x')",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("ref"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "MongoDB ObjectId reference for bi-directional sync",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("slug"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The unique slug identifier for this tape (e.g., wand-1729177200000)",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("thumbnail"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("video"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("when"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "ISO 8601 timestamp when the tape was created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("zipUrl"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Direct URL to download the original ZIP file with frames and audio",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}