// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.tsunagite.song
//
// 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};
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};
/// A song included in a game hosting leaderboards via Tsunagite.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "dev.tsunagite.song",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Song<S: BosStr = DefaultStr> {
    ///The name of the composer of this song. Translations will typically be listed alongside the default.
    pub composer: Data<S>,
    ///The game(s) this song is included in.
    pub game: Vec<AtUri<S>>,
    ///The genre this song belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub genre: Option<Data<S>>,
    ///The jacket or banner art of this song, for display in UI.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jacket: Option<BlobRef<S>>,
    ///The name of the jacket artist for this song.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jacket_artist: Option<Data<S>>,
    ///The source this song is from - an album, competition, other game, etc.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<Data<S>>,
    ///The human-readable subtitle of this song.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subtitle: Option<Data<S>>,
    ///The human-readable title of this song in UI. Translations will typically be listed alongside the default.
    pub title: Data<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 SongGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Song<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct SongRecord;
impl XrpcResp for SongRecord {
    const NSID: &'static str = "dev.tsunagite.song";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = SongGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Song<S> {
    const NSID: &'static str = "dev.tsunagite.song";
    type Record = SongRecord;
}

impl Collection for SongRecord {
    const NSID: &'static str = "dev.tsunagite.song";
    type Record = SongRecord;
}

impl<S: BosStr> LexiconSchema for Song<S> {
    fn nsid() -> &'static str {
        "dev.tsunagite.song"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_tsunagite_song()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.jacket {
            {
                let size = value.blob().size;
                if size > 8000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("jacket"),
                        max: 8000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.jacket {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &[
                    "image/png",
                    "image/jpeg",
                    "image/jxl",
                    "image/webp",
                ];
                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("jacket"),
                        accepted: vec![
                            "image/png".to_string(), "image/jpeg".to_string(),
                            "image/jxl".to_string(), "image/webp".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod song_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 Composer;
        type Game;
        type Title;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Composer = Unset;
        type Game = Unset;
        type Title = Unset;
    }
    ///State transition - sets the `composer` field to Set
    pub struct SetComposer<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetComposer<St> {}
    impl<St: State> State for SetComposer<St> {
        type Composer = Set<members::composer>;
        type Game = St::Game;
        type Title = St::Title;
    }
    ///State transition - sets the `game` field to Set
    pub struct SetGame<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetGame<St> {}
    impl<St: State> State for SetGame<St> {
        type Composer = St::Composer;
        type Game = Set<members::game>;
        type Title = St::Title;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTitle<St> {}
    impl<St: State> State for SetTitle<St> {
        type Composer = St::Composer;
        type Game = St::Game;
        type Title = Set<members::title>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `composer` field
        pub struct composer(());
        ///Marker type for the `game` field
        pub struct game(());
        ///Marker type for the `title` field
        pub struct title(());
    }
}

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

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

impl<S: BosStr> Song<S> {
    /// Create a new builder for this type
    pub fn builder() -> SongBuilder<song_state::Empty, S> {
        SongBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> SongBuilder<St, S>
where
    St: song_state::State,
    St::Composer: song_state::IsUnset,
{
    /// Set the `composer` field (required)
    pub fn composer(
        mut self,
        value: impl Into<Data<S>>,
    ) -> SongBuilder<song_state::SetComposer<St>, S> {
        self._fields.0 = Option::Some(value.into());
        SongBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> SongBuilder<St, S>
where
    St: song_state::State,
    St::Game: song_state::IsUnset,
{
    /// Set the `game` field (required)
    pub fn game(
        mut self,
        value: impl Into<Vec<AtUri<S>>>,
    ) -> SongBuilder<song_state::SetGame<St>, S> {
        self._fields.1 = Option::Some(value.into());
        SongBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: song_state::State, S: BosStr> SongBuilder<St, S> {
    /// Set the `genre` field (optional)
    pub fn genre(mut self, value: impl Into<Option<Data<S>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `genre` field to an Option value (optional)
    pub fn maybe_genre(mut self, value: Option<Data<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

impl<St: song_state::State, S: BosStr> SongBuilder<St, S> {
    /// Set the `jacketArtist` field (optional)
    pub fn jacket_artist(mut self, value: impl Into<Option<Data<S>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `jacketArtist` field to an Option value (optional)
    pub fn maybe_jacket_artist(mut self, value: Option<Data<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: song_state::State, S: BosStr> SongBuilder<St, S> {
    /// Set the `source` field (optional)
    pub fn source(mut self, value: impl Into<Option<Data<S>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `source` field to an Option value (optional)
    pub fn maybe_source(mut self, value: Option<Data<S>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St: song_state::State, S: BosStr> SongBuilder<St, S> {
    /// Set the `subtitle` field (optional)
    pub fn subtitle(mut self, value: impl Into<Option<Data<S>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `subtitle` field to an Option value (optional)
    pub fn maybe_subtitle(mut self, value: Option<Data<S>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St, S: BosStr> SongBuilder<St, S>
where
    St: song_state::State,
    St::Title: song_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<Data<S>>,
    ) -> SongBuilder<song_state::SetTitle<St>, S> {
        self._fields.7 = Option::Some(value.into());
        SongBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> SongBuilder<St, S>
where
    St: song_state::State,
    St::Composer: song_state::IsSet,
    St::Game: song_state::IsSet,
    St::Title: song_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Song<S> {
        Song {
            composer: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            genre: self._fields.2,
            jacket: self._fields.3,
            jacket_artist: self._fields.4,
            source: self._fields.5,
            subtitle: self._fields.6,
            title: self._fields.7.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Song<S> {
        Song {
            composer: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            genre: self._fields.2,
            jacket: self._fields.3,
            jacket_artist: self._fields.4,
            source: self._fields.5,
            subtitle: self._fields.6,
            title: self._fields.7.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_tsunagite_song() -> 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("dev.tsunagite.song"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A song included in a game hosting leaderboards via Tsunagite.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("game"), SmolStr::new_static("title"),
                                SmolStr::new_static("composer")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("composer"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("game"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("The game(s) this song is included in."),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "All URIs must point to records of type `dev.tsunagite.game`.",
                                            ),
                                        ),
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("genre"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("jacket"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("jacketArtist"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("source"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subtitle"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("dev.tsunagite.translatable"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}