// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.tsunagite.chart
//
// 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;
use jacquard_common::deps::bytes::Bytes;

#[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};
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::dev_tsunagite::difficulty::Difficulty;
use crate::dev_tsunagite::types::TypedRef;
/// A chart included in a game hosting leaderboards via Tsunagite.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Chart<'a> {
    ///The difficulty slot this chart is placed in. Can be an inline definition or a reference to a standard-defined difficulty slot.
    #[serde(borrow)]
    pub difficulty: ChartDifficulty<'a>,
    ///The game this chart is included in. URI must point to a record of type `dev.tsunagite.game`.
    #[serde(borrow)]
    pub game: AtUri<'a>,
    ///The jacket or banner art of this chart, for display in UI. Will fall back to the song jacket if not present
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub jacket: Option<BlobRef<'a>>,
    ///The name of the jacket artist for this chart.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub jacket_artist: Option<Data<'a>>,
    ///The md5 hashes of any versions of the chart that are up-to-date enough to be leaderboard-legal. Optional if you will not perform leaderboard resets upon any chart changes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ranked_versions: Option<Vec<Bytes>>,
    ///The numeric difficulty rating displayed to players, formatted as a string to support decimal or + difficulties.
    #[serde(borrow)]
    pub rating: CowStr<'a>,
    ///The song this chart is for. URI must point to a record of type `dev.tsunagite.song`.
    #[serde(borrow)]
    pub song: AtUri<'a>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum ChartDifficulty<'a> {
    #[serde(rename = "dev.tsunagite.difficulty")]
    Difficulty(Box<Difficulty<'a>>),
    #[serde(rename = "dev.tsunagite.types#typedRef")]
    TypesTypedRef(Box<TypedRef<'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 ChartGetRecordOutput<'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: Chart<'a>,
}

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

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

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

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

impl Collection for Chart<'_> {
    const NSID: &'static str = "dev.tsunagite.chart";
    type Record = ChartRecord;
}

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

impl<'a> LexiconSchema for Chart<'a> {
    fn nsid() -> &'static str {
        "dev.tsunagite.chart"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_tsunagite_chart()
    }
    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 chart_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 Game;
        type Song;
        type Difficulty;
        type Rating;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Game = Unset;
        type Song = Unset;
        type Difficulty = Unset;
        type Rating = Unset;
    }
    ///State transition - sets the `game` field to Set
    pub struct SetGame<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetGame<S> {}
    impl<S: State> State for SetGame<S> {
        type Game = Set<members::game>;
        type Song = S::Song;
        type Difficulty = S::Difficulty;
        type Rating = S::Rating;
    }
    ///State transition - sets the `song` field to Set
    pub struct SetSong<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSong<S> {}
    impl<S: State> State for SetSong<S> {
        type Game = S::Game;
        type Song = Set<members::song>;
        type Difficulty = S::Difficulty;
        type Rating = S::Rating;
    }
    ///State transition - sets the `difficulty` field to Set
    pub struct SetDifficulty<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDifficulty<S> {}
    impl<S: State> State for SetDifficulty<S> {
        type Game = S::Game;
        type Song = S::Song;
        type Difficulty = Set<members::difficulty>;
        type Rating = S::Rating;
    }
    ///State transition - sets the `rating` field to Set
    pub struct SetRating<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRating<S> {}
    impl<S: State> State for SetRating<S> {
        type Game = S::Game;
        type Song = S::Song;
        type Difficulty = S::Difficulty;
        type Rating = Set<members::rating>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `game` field
        pub struct game(());
        ///Marker type for the `song` field
        pub struct song(());
        ///Marker type for the `difficulty` field
        pub struct difficulty(());
        ///Marker type for the `rating` field
        pub struct rating(());
    }
}

/// Builder for constructing an instance of this type
pub struct ChartBuilder<'a, S: chart_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<ChartDifficulty<'a>>,
        Option<AtUri<'a>>,
        Option<BlobRef<'a>>,
        Option<Data<'a>>,
        Option<Vec<Bytes>>,
        Option<CowStr<'a>>,
        Option<AtUri<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Chart<'a> {
    /// Create a new builder for this type
    pub fn new() -> ChartBuilder<'a, chart_state::Empty> {
        ChartBuilder::new()
    }
}

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

impl<'a, S> ChartBuilder<'a, S>
where
    S: chart_state::State,
    S::Difficulty: chart_state::IsUnset,
{
    /// Set the `difficulty` field (required)
    pub fn difficulty(
        mut self,
        value: impl Into<ChartDifficulty<'a>>,
    ) -> ChartBuilder<'a, chart_state::SetDifficulty<S>> {
        self._fields.0 = Option::Some(value.into());
        ChartBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ChartBuilder<'a, S>
where
    S: chart_state::State,
    S::Game: chart_state::IsUnset,
{
    /// Set the `game` field (required)
    pub fn game(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> ChartBuilder<'a, chart_state::SetGame<S>> {
        self._fields.1 = Option::Some(value.into());
        ChartBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: chart_state::State> ChartBuilder<'a, S> {
    /// Set the `jacket` field (optional)
    pub fn jacket(mut self, value: impl Into<Option<BlobRef<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `jacket` field to an Option value (optional)
    pub fn maybe_jacket(mut self, value: Option<BlobRef<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: chart_state::State> ChartBuilder<'a, S> {
    /// Set the `jacketArtist` field (optional)
    pub fn jacket_artist(mut self, value: impl Into<Option<Data<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `jacketArtist` field to an Option value (optional)
    pub fn maybe_jacket_artist(mut self, value: Option<Data<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: chart_state::State> ChartBuilder<'a, S> {
    /// Set the `rankedVersions` field (optional)
    pub fn ranked_versions(mut self, value: impl Into<Option<Vec<Bytes>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `rankedVersions` field to an Option value (optional)
    pub fn maybe_ranked_versions(mut self, value: Option<Vec<Bytes>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> ChartBuilder<'a, S>
where
    S: chart_state::State,
    S::Rating: chart_state::IsUnset,
{
    /// Set the `rating` field (required)
    pub fn rating(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> ChartBuilder<'a, chart_state::SetRating<S>> {
        self._fields.5 = Option::Some(value.into());
        ChartBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ChartBuilder<'a, S>
where
    S: chart_state::State,
    S::Song: chart_state::IsUnset,
{
    /// Set the `song` field (required)
    pub fn song(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> ChartBuilder<'a, chart_state::SetSong<S>> {
        self._fields.6 = Option::Some(value.into());
        ChartBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ChartBuilder<'a, S>
where
    S: chart_state::State,
    S::Game: chart_state::IsSet,
    S::Song: chart_state::IsSet,
    S::Difficulty: chart_state::IsSet,
    S::Rating: chart_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Chart<'a> {
        Chart {
            difficulty: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            jacket: self._fields.2,
            jacket_artist: self._fields.3,
            ranked_versions: self._fields.4,
            rating: self._fields.5.unwrap(),
            song: self._fields.6.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, Data<'a>>,
    ) -> Chart<'a> {
        Chart {
            difficulty: self._fields.0.unwrap(),
            game: self._fields.1.unwrap(),
            jacket: self._fields.2,
            jacket_artist: self._fields.3,
            ranked_versions: self._fields.4,
            rating: self._fields.5.unwrap(),
            song: self._fields.6.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_tsunagite_chart() -> 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.chart"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A chart 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("song"),
                                SmolStr::new_static("difficulty"),
                                SmolStr::new_static("rating")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("difficulty"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "The difficulty slot this chart is placed in. Can be an inline definition or a reference to a standard-defined difficulty slot.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("dev.tsunagite.difficulty"),
                                        CowStr::new_static("dev.tsunagite.types#typedRef")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("game"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The game this chart is included in. URI must point to a record of type `dev.tsunagite.game`.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..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("rankedVersions"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "The md5 hashes of any versions of the chart that are up-to-date enough to be leaderboard-legal. Optional if you will not perform leaderboard resets upon any chart changes.",
                                        ),
                                    ),
                                    items: LexArrayItem::Bytes(LexBytes {
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("rating"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The numeric difficulty rating displayed to players, formatted as a string to support decimal or + difficulties.",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("song"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The song this chart is for. URI must point to a record of type `dev.tsunagite.song`.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}