// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.fitsky.trend
//
// 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};
use crate::app_fitsky::trend;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct DataPoint<S: BosStr = DefaultStr> {
    pub date: Datetime,
    ///Value in base units (meters, seconds, calories, count, bpm)
    pub value: i64,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A shared fitness trend or dashboard snapshot

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.fitsky.trend",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Trend<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub caption: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chart_style: Option<TrendChartStyle<S>>,
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_points: Option<Vec<trend::DataPoint<S>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<BlobRef<S>>,
    pub metric: TrendMetric<S>,
    pub period: TrendPeriod<S>,
    pub summary: trend::TrendSummary<S>,
    pub widget_type: TrendWidgetType<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TrendChartStyle<S: BosStr = DefaultStr> {
    Line,
    Bar,
    Other(S),
}

impl<S: BosStr> TrendChartStyle<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Line => "line",
            Self::Bar => "bar",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "line" => Self::Line,
            "bar" => Self::Bar,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for TrendChartStyle<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for TrendChartStyle<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for TrendChartStyle<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for TrendChartStyle<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for TrendChartStyle<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for TrendChartStyle<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = TrendChartStyle<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            TrendChartStyle::Line => TrendChartStyle::Line,
            TrendChartStyle::Bar => TrendChartStyle::Bar,
            TrendChartStyle::Other(v) => TrendChartStyle::Other(v.into_static()),
        }
    }
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TrendMetric<S: BosStr = DefaultStr> {
    Distance,
    Duration,
    Pace,
    Steps,
    Calories,
    HeartRate,
    WorkoutCount,
    Other(S),
}

impl<S: BosStr> TrendMetric<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Distance => "distance",
            Self::Duration => "duration",
            Self::Pace => "pace",
            Self::Steps => "steps",
            Self::Calories => "calories",
            Self::HeartRate => "heartRate",
            Self::WorkoutCount => "workoutCount",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "distance" => Self::Distance,
            "duration" => Self::Duration,
            "pace" => Self::Pace,
            "steps" => Self::Steps,
            "calories" => Self::Calories,
            "heartRate" => Self::HeartRate,
            "workoutCount" => Self::WorkoutCount,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for TrendMetric<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for TrendMetric<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for TrendMetric<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for TrendMetric<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for TrendMetric<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for TrendMetric<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = TrendMetric<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            TrendMetric::Distance => TrendMetric::Distance,
            TrendMetric::Duration => TrendMetric::Duration,
            TrendMetric::Pace => TrendMetric::Pace,
            TrendMetric::Steps => TrendMetric::Steps,
            TrendMetric::Calories => TrendMetric::Calories,
            TrendMetric::HeartRate => TrendMetric::HeartRate,
            TrendMetric::WorkoutCount => TrendMetric::WorkoutCount,
            TrendMetric::Other(v) => TrendMetric::Other(v.into_static()),
        }
    }
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TrendPeriod<S: BosStr = DefaultStr> {
    _1d,
    _7d,
    _30d,
    _90d,
    _1y,
    Other(S),
}

impl<S: BosStr> TrendPeriod<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::_1d => "1d",
            Self::_7d => "7d",
            Self::_30d => "30d",
            Self::_90d => "90d",
            Self::_1y => "1y",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "1d" => Self::_1d,
            "7d" => Self::_7d,
            "30d" => Self::_30d,
            "90d" => Self::_90d,
            "1y" => Self::_1y,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for TrendPeriod<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for TrendPeriod<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for TrendPeriod<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for TrendPeriod<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for TrendPeriod<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for TrendPeriod<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = TrendPeriod<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            TrendPeriod::_1d => TrendPeriod::_1d,
            TrendPeriod::_7d => TrendPeriod::_7d,
            TrendPeriod::_30d => TrendPeriod::_30d,
            TrendPeriod::_90d => TrendPeriod::_90d,
            TrendPeriod::_1y => TrendPeriod::_1y,
            TrendPeriod::Other(v) => TrendPeriod::Other(v.into_static()),
        }
    }
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TrendWidgetType<S: BosStr = DefaultStr> {
    TodaySummary,
    WeeklyProgress,
    GoalProgress,
    RecentWorkouts,
    CustomTrend,
    Other(S),
}

impl<S: BosStr> TrendWidgetType<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::TodaySummary => "today-summary",
            Self::WeeklyProgress => "weekly-progress",
            Self::GoalProgress => "goal-progress",
            Self::RecentWorkouts => "recent-workouts",
            Self::CustomTrend => "custom-trend",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "today-summary" => Self::TodaySummary,
            "weekly-progress" => Self::WeeklyProgress,
            "goal-progress" => Self::GoalProgress,
            "recent-workouts" => Self::RecentWorkouts,
            "custom-trend" => Self::CustomTrend,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for TrendWidgetType<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for TrendWidgetType<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for TrendWidgetType<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for TrendWidgetType<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for TrendWidgetType<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for TrendWidgetType<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = TrendWidgetType<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            TrendWidgetType::TodaySummary => TrendWidgetType::TodaySummary,
            TrendWidgetType::WeeklyProgress => TrendWidgetType::WeeklyProgress,
            TrendWidgetType::GoalProgress => TrendWidgetType::GoalProgress,
            TrendWidgetType::RecentWorkouts => TrendWidgetType::RecentWorkouts,
            TrendWidgetType::CustomTrend => TrendWidgetType::CustomTrend,
            TrendWidgetType::Other(v) => TrendWidgetType::Other(v.into_static()),
        }
    }
}

/// 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 TrendGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Trend<S>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct TrendSummary<S: BosStr = DefaultStr> {
    ///Average value in base units
    #[serde(skip_serializing_if = "Option::is_none")]
    pub average: Option<i64>,
    ///Best value in base units
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<i64>,
    ///Total value in base units
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total: Option<i64>,
    ///Worst value in base units
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worst: Option<i64>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

impl<S: BosStr> LexiconSchema for DataPoint<S> {
    fn nsid() -> &'static str {
        "app.fitsky.trend"
    }
    fn def_name() -> &'static str {
        "dataPoint"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_fitsky_trend()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

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

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

impl<S: BosStr> Collection for Trend<S> {
    const NSID: &'static str = "app.fitsky.trend";
    type Record = TrendRecord;
}

impl Collection for TrendRecord {
    const NSID: &'static str = "app.fitsky.trend";
    type Record = TrendRecord;
}

impl<S: BosStr> LexiconSchema for Trend<S> {
    fn nsid() -> &'static str {
        "app.fitsky.trend"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_fitsky_trend()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.caption {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("caption"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.chart_style {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("chart_style"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.image {
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("image"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        if let Some(ref value) = self.image {
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/png", "image/jpeg"];
                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("image"),
                        accepted: vec![
                            "image/png".to_string(), "image/jpeg".to_string()
                        ],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        {
            let value = &self.metric;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("metric"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.period;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("period"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.widget_type;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("widget_type"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for TrendSummary<S> {
    fn nsid() -> &'static str {
        "app.fitsky.trend"
    }
    fn def_name() -> &'static str {
        "trendSummary"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_fitsky_trend()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

pub mod data_point_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 Date;
        type Value;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Date = Unset;
        type Value = Unset;
    }
    ///State transition - sets the `date` field to Set
    pub struct SetDate<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDate<St> {}
    impl<St: State> State for SetDate<St> {
        type Date = Set<members::date>;
        type Value = St::Value;
    }
    ///State transition - sets the `value` field to Set
    pub struct SetValue<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetValue<St> {}
    impl<St: State> State for SetValue<St> {
        type Date = St::Date;
        type Value = Set<members::value>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `date` field
        pub struct date(());
        ///Marker type for the `value` field
        pub struct value(());
    }
}

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

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

impl<S: BosStr> DataPoint<S> {
    /// Create a new builder for this type
    pub fn builder() -> DataPointBuilder<data_point_state::Empty, S> {
        DataPointBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> DataPointBuilder<St, S>
where
    St: data_point_state::State,
    St::Date: data_point_state::IsUnset,
{
    /// Set the `date` field (required)
    pub fn date(
        mut self,
        value: impl Into<Datetime>,
    ) -> DataPointBuilder<data_point_state::SetDate<St>, S> {
        self._fields.0 = Option::Some(value.into());
        DataPointBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DataPointBuilder<St, S>
where
    St: data_point_state::State,
    St::Value: data_point_state::IsUnset,
{
    /// Set the `value` field (required)
    pub fn value(
        mut self,
        value: impl Into<i64>,
    ) -> DataPointBuilder<data_point_state::SetValue<St>, S> {
        self._fields.1 = Option::Some(value.into());
        DataPointBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DataPointBuilder<St, S>
where
    St: data_point_state::State,
    St::Date: data_point_state::IsSet,
    St::Value: data_point_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> DataPoint<S> {
        DataPoint {
            date: self._fields.0.unwrap(),
            value: self._fields.1.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>>,
    ) -> DataPoint<S> {
        DataPoint {
            date: self._fields.0.unwrap(),
            value: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_fitsky_trend() -> 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("app.fitsky.trend"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("dataPoint"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![SmolStr::new_static("date"), SmolStr::new_static("value")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("date"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("value"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A shared fitness trend or dashboard snapshot",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("widgetType"),
                                SmolStr::new_static("metric"),
                                SmolStr::new_static("period"),
                                SmolStr::new_static("summary"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("caption"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("chartStyle"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("dataPoints"),
                                LexObjectProperty::Array(LexArray {
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#dataPoint"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("image"),
                                LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                            );
                            map.insert(
                                SmolStr::new_static("metric"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("period"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("summary"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#trendSummary"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("widgetType"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("trendSummary"),
                LexUserType::Object(LexObject {
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("average"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("best"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("count"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("total"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("worst"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod trend_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 CreatedAt;
        type Metric;
        type Period;
        type Summary;
        type WidgetType;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Metric = Unset;
        type Period = Unset;
        type Summary = Unset;
        type WidgetType = Unset;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCreatedAt<St> {}
    impl<St: State> State for SetCreatedAt<St> {
        type CreatedAt = Set<members::created_at>;
        type Metric = St::Metric;
        type Period = St::Period;
        type Summary = St::Summary;
        type WidgetType = St::WidgetType;
    }
    ///State transition - sets the `metric` field to Set
    pub struct SetMetric<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetMetric<St> {}
    impl<St: State> State for SetMetric<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = Set<members::metric>;
        type Period = St::Period;
        type Summary = St::Summary;
        type WidgetType = St::WidgetType;
    }
    ///State transition - sets the `period` field to Set
    pub struct SetPeriod<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPeriod<St> {}
    impl<St: State> State for SetPeriod<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = St::Metric;
        type Period = Set<members::period>;
        type Summary = St::Summary;
        type WidgetType = St::WidgetType;
    }
    ///State transition - sets the `summary` field to Set
    pub struct SetSummary<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSummary<St> {}
    impl<St: State> State for SetSummary<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = St::Metric;
        type Period = St::Period;
        type Summary = Set<members::summary>;
        type WidgetType = St::WidgetType;
    }
    ///State transition - sets the `widget_type` field to Set
    pub struct SetWidgetType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetWidgetType<St> {}
    impl<St: State> State for SetWidgetType<St> {
        type CreatedAt = St::CreatedAt;
        type Metric = St::Metric;
        type Period = St::Period;
        type Summary = St::Summary;
        type WidgetType = Set<members::widget_type>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `metric` field
        pub struct metric(());
        ///Marker type for the `period` field
        pub struct period(());
        ///Marker type for the `summary` field
        pub struct summary(());
        ///Marker type for the `widget_type` field
        pub struct widget_type(());
    }
}

/// Builder for constructing an instance of this type.
pub struct TrendBuilder<St: trend_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<S>,
        Option<TrendChartStyle<S>>,
        Option<Datetime>,
        Option<Vec<trend::DataPoint<S>>>,
        Option<BlobRef<S>>,
        Option<TrendMetric<S>>,
        Option<TrendPeriod<S>>,
        Option<trend::TrendSummary<S>>,
        Option<TrendWidgetType<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Trend<S> {
    /// Create a new builder for this type
    pub fn builder() -> TrendBuilder<trend_state::Empty, S> {
        TrendBuilder::builder()
    }
}

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

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

impl<St: trend_state::State, S: BosStr> TrendBuilder<St, S> {
    /// Set the `caption` field (optional)
    pub fn caption(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `caption` field to an Option value (optional)
    pub fn maybe_caption(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: trend_state::State, S: BosStr> TrendBuilder<St, S> {
    /// Set the `chartStyle` field (optional)
    pub fn chart_style(mut self, value: impl Into<Option<TrendChartStyle<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `chartStyle` field to an Option value (optional)
    pub fn maybe_chart_style(mut self, value: Option<TrendChartStyle<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> TrendBuilder<St, S>
where
    St: trend_state::State,
    St::CreatedAt: trend_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> TrendBuilder<trend_state::SetCreatedAt<St>, S> {
        self._fields.2 = Option::Some(value.into());
        TrendBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: trend_state::State, S: BosStr> TrendBuilder<St, S> {
    /// Set the `dataPoints` field (optional)
    pub fn data_points(
        mut self,
        value: impl Into<Option<Vec<trend::DataPoint<S>>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `dataPoints` field to an Option value (optional)
    pub fn maybe_data_points(mut self, value: Option<Vec<trend::DataPoint<S>>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: trend_state::State, S: BosStr> TrendBuilder<St, S> {
    /// Set the `image` field (optional)
    pub fn image(mut self, value: impl Into<Option<BlobRef<S>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `image` field to an Option value (optional)
    pub fn maybe_image(mut self, value: Option<BlobRef<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> TrendBuilder<St, S>
where
    St: trend_state::State,
    St::Metric: trend_state::IsUnset,
{
    /// Set the `metric` field (required)
    pub fn metric(
        mut self,
        value: impl Into<TrendMetric<S>>,
    ) -> TrendBuilder<trend_state::SetMetric<St>, S> {
        self._fields.5 = Option::Some(value.into());
        TrendBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> TrendBuilder<St, S>
where
    St: trend_state::State,
    St::Period: trend_state::IsUnset,
{
    /// Set the `period` field (required)
    pub fn period(
        mut self,
        value: impl Into<TrendPeriod<S>>,
    ) -> TrendBuilder<trend_state::SetPeriod<St>, S> {
        self._fields.6 = Option::Some(value.into());
        TrendBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> TrendBuilder<St, S>
where
    St: trend_state::State,
    St::Summary: trend_state::IsUnset,
{
    /// Set the `summary` field (required)
    pub fn summary(
        mut self,
        value: impl Into<trend::TrendSummary<S>>,
    ) -> TrendBuilder<trend_state::SetSummary<St>, S> {
        self._fields.7 = Option::Some(value.into());
        TrendBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> TrendBuilder<St, S>
where
    St: trend_state::State,
    St::WidgetType: trend_state::IsUnset,
{
    /// Set the `widgetType` field (required)
    pub fn widget_type(
        mut self,
        value: impl Into<TrendWidgetType<S>>,
    ) -> TrendBuilder<trend_state::SetWidgetType<St>, S> {
        self._fields.8 = Option::Some(value.into());
        TrendBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> TrendBuilder<St, S>
where
    St: trend_state::State,
    St::CreatedAt: trend_state::IsSet,
    St::Metric: trend_state::IsSet,
    St::Period: trend_state::IsSet,
    St::Summary: trend_state::IsSet,
    St::WidgetType: trend_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Trend<S> {
        Trend {
            caption: self._fields.0,
            chart_style: self._fields.1,
            created_at: self._fields.2.unwrap(),
            data_points: self._fields.3,
            image: self._fields.4,
            metric: self._fields.5.unwrap(),
            period: self._fields.6.unwrap(),
            summary: self._fields.7.unwrap(),
            widget_type: self._fields.8.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>>) -> Trend<S> {
        Trend {
            caption: self._fields.0,
            chart_style: self._fields.1,
            created_at: self._fields.2.unwrap(),
            data_points: self._fields.3,
            image: self._fields.4,
            metric: self._fields.5.unwrap(),
            period: self._fields.6.unwrap(),
            summary: self._fields.7.unwrap(),
            widget_type: self._fields.8.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}