// @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, 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};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
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};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "computer.aesthetic.tape",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Tape<S: BosStr = DefaultStr> {
    ///Permanent link to view on aesthetic.computer (e.g., https://aesthetic.computer/!a3x)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ac_url: Option<S>,
    ///Short alphanumeric code for easy lookup (e.g., 'a3x')
    pub code: S,
    ///MongoDB ObjectId reference for bi-directional sync
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#ref: Option<S>,
    ///The unique slug identifier for this tape (e.g., wand-1729177200000)
    pub slug: S,
    ///Thumbnail image from midpoint frame, 3x scaled with nearest neighbor (max 1MB)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail: Option<BlobRef<S>>,
    ///MP4 video with 3x pixel scaling and audio soundtrack (max 50MB)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub video: Option<BlobRef<S>>,
    ///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")]
    pub zip_url: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<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 TapeGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Tape<S>,
}

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

/// 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<S: BosStr> = TapeGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

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

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

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

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

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

impl<St: tape_state::State, S: BosStr> TapeBuilder<St, S> {
    /// Set the `acUrl` field (optional)
    pub fn ac_url(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

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

impl<St: tape_state::State, S: BosStr> TapeBuilder<St, S> {
    /// Set the `thumbnail` field (optional)
    pub fn thumbnail(mut self, value: impl Into<Option<BlobRef<S>>>) -> 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<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: tape_state::State, S: BosStr> TapeBuilder<St, S> {
    /// Set the `video` field (optional)
    pub fn video(mut self, value: impl Into<Option<BlobRef<S>>>) -> 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<S>>) -> Self {
        self._fields.5 = value;
        self
    }
}

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

impl<St: tape_state::State, S: BosStr> TapeBuilder<St, S> {
    /// Set the `zipUrl` field (optional)
    pub fn zip_url(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St, S: BosStr> TapeBuilder<St, S>
where
    St: tape_state::State,
    St::Code: tape_state::IsSet,
    St::Slug: tape_state::IsSet,
    St::When: tape_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Tape<S> {
        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<SmolStr, Data<S>>) -> Tape<S> {
        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()
    }
}