// @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;

#[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, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
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;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct DataPoint<'a> {
    pub date: Datetime,
    ///Value in base units (meters, seconds, calories, count, bpm)
    pub value: i64,
}

/// A shared fitness trend or dashboard snapshot

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Trend<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub caption: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub chart_style: Option<TrendChartStyle<'a>>,
    pub created_at: Datetime,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub data_points: Option<Vec<trend::DataPoint<'a>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub image: Option<BlobRef<'a>>,
    #[serde(borrow)]
    pub metric: TrendMetric<'a>,
    #[serde(borrow)]
    pub period: TrendPeriod<'a>,
    #[serde(borrow)]
    pub summary: trend::TrendSummary<'a>,
    #[serde(borrow)]
    pub widget_type: TrendWidgetType<'a>,
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TrendChartStyle<'a> {
    Line,
    Bar,
    Other(CowStr<'a>),
}

impl<'a> TrendChartStyle<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Line => "line",
            Self::Bar => "bar",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for TrendChartStyle<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "line" => Self::Line,
            "bar" => Self::Bar,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for TrendChartStyle<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "line" => Self::Line,
            "bar" => Self::Bar,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for TrendChartStyle<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for TrendChartStyle<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for TrendChartStyle<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for TrendChartStyle<'_> {
    type Output = TrendChartStyle<'static>;
    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<'a> {
    Distance,
    Duration,
    Pace,
    Steps,
    Calories,
    HeartRate,
    WorkoutCount,
    Other(CowStr<'a>),
}

impl<'a> TrendMetric<'a> {
    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(),
        }
    }
}

impl<'a> From<&'a str> for TrendMetric<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "distance" => Self::Distance,
            "duration" => Self::Duration,
            "pace" => Self::Pace,
            "steps" => Self::Steps,
            "calories" => Self::Calories,
            "heartRate" => Self::HeartRate,
            "workoutCount" => Self::WorkoutCount,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for TrendMetric<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "distance" => Self::Distance,
            "duration" => Self::Duration,
            "pace" => Self::Pace,
            "steps" => Self::Steps,
            "calories" => Self::Calories,
            "heartRate" => Self::HeartRate,
            "workoutCount" => Self::WorkoutCount,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for TrendMetric<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for TrendMetric<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for TrendMetric<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for TrendMetric<'_> {
    type Output = TrendMetric<'static>;
    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<'a> {
    _1d,
    _7d,
    _30d,
    _90d,
    _1y,
    Other(CowStr<'a>),
}

impl<'a> TrendPeriod<'a> {
    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(),
        }
    }
}

impl<'a> From<&'a str> for TrendPeriod<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "1d" => Self::_1d,
            "7d" => Self::_7d,
            "30d" => Self::_30d,
            "90d" => Self::_90d,
            "1y" => Self::_1y,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for TrendPeriod<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "1d" => Self::_1d,
            "7d" => Self::_7d,
            "30d" => Self::_30d,
            "90d" => Self::_90d,
            "1y" => Self::_1y,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for TrendPeriod<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for TrendPeriod<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for TrendPeriod<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for TrendPeriod<'_> {
    type Output = TrendPeriod<'static>;
    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<'a> {
    TodaySummary,
    WeeklyProgress,
    GoalProgress,
    RecentWorkouts,
    CustomTrend,
    Other(CowStr<'a>),
}

impl<'a> TrendWidgetType<'a> {
    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(),
        }
    }
}

impl<'a> From<&'a str> for TrendWidgetType<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "today-summary" => Self::TodaySummary,
            "weekly-progress" => Self::WeeklyProgress,
            "goal-progress" => Self::GoalProgress,
            "recent-workouts" => Self::RecentWorkouts,
            "custom-trend" => Self::CustomTrend,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for TrendWidgetType<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "today-summary" => Self::TodaySummary,
            "weekly-progress" => Self::WeeklyProgress,
            "goal-progress" => Self::GoalProgress,
            "recent-workouts" => Self::RecentWorkouts,
            "custom-trend" => Self::CustomTrend,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for TrendWidgetType<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for TrendWidgetType<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for TrendWidgetType<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for TrendWidgetType<'_> {
    type Output = TrendWidgetType<'static>;
    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<'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: Trend<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct TrendSummary<'a> {
    ///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>,
}

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

impl<'a> LexiconSchema for DataPoint<'a> {
    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<'de> = TrendGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Trend<'_> {
    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<'a> LexiconSchema for Trend<'a> {
    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<'a> LexiconSchema for TrendSummary<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetDate<S> {}
    impl<S: State> State for SetDate<S> {
        type Date = Set<members::date>;
        type Value = S::Value;
    }
    ///State transition - sets the `value` field to Set
    pub struct SetValue<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetValue<S> {}
    impl<S: State> State for SetValue<S> {
        type Date = S::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<'a, S: data_point_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<Datetime>, Option<i64>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> DataPointBuilder<'a, S>
where
    S: data_point_state::State,
    S::Date: data_point_state::IsSet,
    S::Value: data_point_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> DataPoint<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> DataPoint<'a> {
        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 Metric;
        type WidgetType;
        type CreatedAt;
        type Summary;
        type Period;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Metric = Unset;
        type WidgetType = Unset;
        type CreatedAt = Unset;
        type Summary = Unset;
        type Period = Unset;
    }
    ///State transition - sets the `metric` field to Set
    pub struct SetMetric<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetMetric<S> {}
    impl<S: State> State for SetMetric<S> {
        type Metric = Set<members::metric>;
        type WidgetType = S::WidgetType;
        type CreatedAt = S::CreatedAt;
        type Summary = S::Summary;
        type Period = S::Period;
    }
    ///State transition - sets the `widget_type` field to Set
    pub struct SetWidgetType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetWidgetType<S> {}
    impl<S: State> State for SetWidgetType<S> {
        type Metric = S::Metric;
        type WidgetType = Set<members::widget_type>;
        type CreatedAt = S::CreatedAt;
        type Summary = S::Summary;
        type Period = S::Period;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type Metric = S::Metric;
        type WidgetType = S::WidgetType;
        type CreatedAt = Set<members::created_at>;
        type Summary = S::Summary;
        type Period = S::Period;
    }
    ///State transition - sets the `summary` field to Set
    pub struct SetSummary<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSummary<S> {}
    impl<S: State> State for SetSummary<S> {
        type Metric = S::Metric;
        type WidgetType = S::WidgetType;
        type CreatedAt = S::CreatedAt;
        type Summary = Set<members::summary>;
        type Period = S::Period;
    }
    ///State transition - sets the `period` field to Set
    pub struct SetPeriod<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPeriod<S> {}
    impl<S: State> State for SetPeriod<S> {
        type Metric = S::Metric;
        type WidgetType = S::WidgetType;
        type CreatedAt = S::CreatedAt;
        type Summary = S::Summary;
        type Period = Set<members::period>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `metric` field
        pub struct metric(());
        ///Marker type for the `widget_type` field
        pub struct widget_type(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `summary` field
        pub struct summary(());
        ///Marker type for the `period` field
        pub struct period(());
    }
}

/// Builder for constructing an instance of this type
pub struct TrendBuilder<'a, S: trend_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<TrendChartStyle<'a>>,
        Option<Datetime>,
        Option<Vec<trend::DataPoint<'a>>>,
        Option<BlobRef<'a>>,
        Option<TrendMetric<'a>>,
        Option<TrendPeriod<'a>>,
        Option<trend::TrendSummary<'a>>,
        Option<TrendWidgetType<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

impl<'a, S: trend_state::State> TrendBuilder<'a, S> {
    /// Set the `chartStyle` field (optional)
    pub fn chart_style(mut self, value: impl Into<Option<TrendChartStyle<'a>>>) -> 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<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<'a, S: trend_state::State> TrendBuilder<'a, S> {
    /// Set the `dataPoints` field (optional)
    pub fn data_points(
        mut self,
        value: impl Into<Option<Vec<trend::DataPoint<'a>>>>,
    ) -> 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<'a>>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: trend_state::State> TrendBuilder<'a, S> {
    /// Set the `image` field (optional)
    pub fn image(mut self, value: impl Into<Option<BlobRef<'a>>>) -> 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<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

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

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

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

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

impl<'a, S> TrendBuilder<'a, S>
where
    S: trend_state::State,
    S::Metric: trend_state::IsSet,
    S::WidgetType: trend_state::IsSet,
    S::CreatedAt: trend_state::IsSet,
    S::Summary: trend_state::IsSet,
    S::Period: trend_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Trend<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Trend<'a> {
        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),
        }
    }
}