// @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, BosStr, DefaultStr, FromStaticStr};
use jacquard_common::deps::bytes::Bytes;

#[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, 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.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "dev.tsunagite.chart",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Chart<S: BosStr = DefaultStr> {
    ///The difficulty slot this chart is placed in. Can be an inline definition or a reference to a standard-defined difficulty slot.
    pub difficulty: ChartDifficulty<S>,
    ///The game this chart is included in. URI must point to a record of type `dev.tsunagite.game`.
    pub game: AtUri<S>,
    ///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")]
    pub jacket: Option<BlobRef<S>>,
    ///The name of the jacket artist for this chart.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jacket_artist: Option<Data<S>>,
    ///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.
    pub rating: S,
    ///The song this chart is for. URI must point to a record of type `dev.tsunagite.song`.
    pub song: AtUri<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 ChartDifficulty<S: BosStr = DefaultStr> {
    #[serde(rename = "dev.tsunagite.difficulty")]
    Difficulty(Box<Difficulty<S>>),
    #[serde(rename = "dev.tsunagite.types#typedRef")]
    TypesTypedRef(Box<TypedRef<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 ChartGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Chart<S>,
}

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

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

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

impl<S: BosStr> Collection for Chart<S> {
    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<S: BosStr> LexiconSchema for Chart<S> {
    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 Difficulty;
        type Game;
        type Rating;
        type Song;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Difficulty = Unset;
        type Game = Unset;
        type Rating = Unset;
        type Song = Unset;
    }
    ///State transition - sets the `difficulty` field to Set
    pub struct SetDifficulty<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDifficulty<St> {}
    impl<St: State> State for SetDifficulty<St> {
        type Difficulty = Set<members::difficulty>;
        type Game = St::Game;
        type Rating = St::Rating;
        type Song = St::Song;
    }
    ///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 Difficulty = St::Difficulty;
        type Game = Set<members::game>;
        type Rating = St::Rating;
        type Song = St::Song;
    }
    ///State transition - sets the `rating` field to Set
    pub struct SetRating<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRating<St> {}
    impl<St: State> State for SetRating<St> {
        type Difficulty = St::Difficulty;
        type Game = St::Game;
        type Rating = Set<members::rating>;
        type Song = St::Song;
    }
    ///State transition - sets the `song` field to Set
    pub struct SetSong<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSong<St> {}
    impl<St: State> State for SetSong<St> {
        type Difficulty = St::Difficulty;
        type Game = St::Game;
        type Rating = St::Rating;
        type Song = Set<members::song>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `difficulty` field
        pub struct difficulty(());
        ///Marker type for the `game` field
        pub struct game(());
        ///Marker type for the `rating` field
        pub struct rating(());
        ///Marker type for the `song` field
        pub struct song(());
    }
}

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

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

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

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

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

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

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

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

impl<St: chart_state::State, S: BosStr> ChartBuilder<St, S> {
    /// Set the `jacketArtist` field (optional)
    pub fn jacket_artist(mut self, value: impl Into<Option<Data<S>>>) -> 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<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: chart_state::State, S: BosStr> ChartBuilder<St, 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<St, S: BosStr> ChartBuilder<St, S>
where
    St: chart_state::State,
    St::Rating: chart_state::IsUnset,
{
    /// Set the `rating` field (required)
    pub fn rating(
        mut self,
        value: impl Into<S>,
    ) -> ChartBuilder<chart_state::SetRating<St>, S> {
        self._fields.5 = Option::Some(value.into());
        ChartBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> ChartBuilder<St, S>
where
    St: chart_state::State,
    St::Difficulty: chart_state::IsSet,
    St::Game: chart_state::IsSet,
    St::Rating: chart_state::IsSet,
    St::Song: chart_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Chart<S> {
        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<SmolStr, Data<S>>) -> Chart<S> {
        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()
    }
}