// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: dev.sensorthings.multiObservation
//
// 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::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, 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_sensorthings::datastream::UnitOfMeasurement;
use crate::dev_sensorthings::multi_observation;
/// A composite observation bundling multiple co-produced results from a single act of sensing. Each entry carries its own ObservedProperty, unit, and scale metadata. Use this instead of separate Observations when the results are genuinely co-produced (e.g. wave statistics from spectral processing) and have no independent existence.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "dev.sensorthings.multiObservation",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct MultiObservation<S: BosStr = DefaultStr> {
    ///AT-URIs of source observations or datastreams
    #[serde(skip_serializing_if = "Option::is_none")]
    pub derived_from: Option<Vec<AtUri<S>>>,
    ///Array of co-produced result entries
    pub entries: Vec<multi_observation::MultiObservationEntry<S>>,
    ///Time the phenomenon was observed. Start of interval if phenomenonTimeEnd is present.
    pub phenomenon_time: Datetime,
    ///End of observation interval. For wave statistics, this is the end of the burst window.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phenomenon_time_end: Option<Datetime>,
    ///Quality flag applying to the composite observation as a whole
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_quality: Option<MultiObservationResultQuality<S>>,
    ///Time the results became available
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_time: Option<Datetime>,
    ///AT-URI of the dev.sensorthings.sensor record (the instrument or process that co-produced these results)
    pub sensor: AtUri<S>,
    ///AT-URI of the dev.sensorthings.thing record
    pub thing: AtUri<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Quality flag applying to the composite observation as a whole

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MultiObservationResultQuality<S: BosStr = DefaultStr> {
    Good,
    Suspect,
    Missing,
    Other(S),
}

impl<S: BosStr> MultiObservationResultQuality<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Good => "dev.sensorthings.quality#good",
            Self::Suspect => "dev.sensorthings.quality#suspect",
            Self::Missing => "dev.sensorthings.quality#missing",
            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() {
            "dev.sensorthings.quality#good" => Self::Good,
            "dev.sensorthings.quality#suspect" => Self::Suspect,
            "dev.sensorthings.quality#missing" => Self::Missing,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for MultiObservationResultQuality<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 MultiObservationResultQuality<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 MultiObservationResultQuality<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for MultiObservationResultQuality<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = MultiObservationResultQuality<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            MultiObservationResultQuality::Good => MultiObservationResultQuality::Good,
            MultiObservationResultQuality::Suspect => {
                MultiObservationResultQuality::Suspect
            }
            MultiObservationResultQuality::Missing => {
                MultiObservationResultQuality::Missing
            }
            MultiObservationResultQuality::Other(v) => {
                MultiObservationResultQuality::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 MultiObservationGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: MultiObservation<S>,
}

/// A single result within a composite observation, fully self-describing.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct MultiObservationEntry<S: BosStr = DefaultStr> {
    ///AT-URI of the dev.sensorthings.observedProperty record
    pub observed_property: AtUri<S>,
    pub result: MultiObservationEntryResult<S>,
    ///Quality flag for this specific entry, if different from the composite quality
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_quality: Option<MultiObservationEntryResultQuality<S>>,
    ///Scale factor for this entry's numeric result. Default 0.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_scale_factor: Option<i64>,
    pub unit_of_measurement: UnitOfMeasurement<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 MultiObservationEntryResult<S: BosStr = DefaultStr> {}
/// Quality flag for this specific entry, if different from the composite quality

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MultiObservationEntryResultQuality<S: BosStr = DefaultStr> {
    Good,
    Suspect,
    Missing,
    Other(S),
}

impl<S: BosStr> MultiObservationEntryResultQuality<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Good => "dev.sensorthings.quality#good",
            Self::Suspect => "dev.sensorthings.quality#suspect",
            Self::Missing => "dev.sensorthings.quality#missing",
            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() {
            "dev.sensorthings.quality#good" => Self::Good,
            "dev.sensorthings.quality#suspect" => Self::Suspect,
            "dev.sensorthings.quality#missing" => Self::Missing,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for MultiObservationEntryResultQuality<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 MultiObservationEntryResultQuality<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 MultiObservationEntryResultQuality<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

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

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

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

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

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

impl<S: BosStr> Collection for MultiObservation<S> {
    const NSID: &'static str = "dev.sensorthings.multiObservation";
    type Record = MultiObservationRecord;
}

impl Collection for MultiObservationRecord {
    const NSID: &'static str = "dev.sensorthings.multiObservation";
    type Record = MultiObservationRecord;
}

impl<S: BosStr> LexiconSchema for MultiObservation<S> {
    fn nsid() -> &'static str {
        "dev.sensorthings.multiObservation"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_sensorthings_multiObservation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.derived_from {
            #[allow(unused_comparisons)]
            if value.len() > 16usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("derived_from"),
                    max: 16usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.entries;
            #[allow(unused_comparisons)]
            if value.len() > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("entries"),
                    max: 32usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.result_quality {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("result_quality"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for MultiObservationEntry<S> {
    fn nsid() -> &'static str {
        "dev.sensorthings.multiObservation"
    }
    fn def_name() -> &'static str {
        "multiObservationEntry"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_dev_sensorthings_multiObservation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.result_quality {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("result_quality"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod multi_observation_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 Entries;
        type PhenomenonTime;
        type Sensor;
        type Thing;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Entries = Unset;
        type PhenomenonTime = Unset;
        type Sensor = Unset;
        type Thing = Unset;
    }
    ///State transition - sets the `entries` field to Set
    pub struct SetEntries<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetEntries<St> {}
    impl<St: State> State for SetEntries<St> {
        type Entries = Set<members::entries>;
        type PhenomenonTime = St::PhenomenonTime;
        type Sensor = St::Sensor;
        type Thing = St::Thing;
    }
    ///State transition - sets the `phenomenon_time` field to Set
    pub struct SetPhenomenonTime<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPhenomenonTime<St> {}
    impl<St: State> State for SetPhenomenonTime<St> {
        type Entries = St::Entries;
        type PhenomenonTime = Set<members::phenomenon_time>;
        type Sensor = St::Sensor;
        type Thing = St::Thing;
    }
    ///State transition - sets the `sensor` field to Set
    pub struct SetSensor<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSensor<St> {}
    impl<St: State> State for SetSensor<St> {
        type Entries = St::Entries;
        type PhenomenonTime = St::PhenomenonTime;
        type Sensor = Set<members::sensor>;
        type Thing = St::Thing;
    }
    ///State transition - sets the `thing` field to Set
    pub struct SetThing<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetThing<St> {}
    impl<St: State> State for SetThing<St> {
        type Entries = St::Entries;
        type PhenomenonTime = St::PhenomenonTime;
        type Sensor = St::Sensor;
        type Thing = Set<members::thing>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `entries` field
        pub struct entries(());
        ///Marker type for the `phenomenon_time` field
        pub struct phenomenon_time(());
        ///Marker type for the `sensor` field
        pub struct sensor(());
        ///Marker type for the `thing` field
        pub struct thing(());
    }
}

/// Builder for constructing an instance of this type.
pub struct MultiObservationBuilder<
    St: multi_observation_state::State,
    S: BosStr = DefaultStr,
> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<AtUri<S>>>,
        Option<Vec<multi_observation::MultiObservationEntry<S>>>,
        Option<Datetime>,
        Option<Datetime>,
        Option<MultiObservationResultQuality<S>>,
        Option<Datetime>,
        Option<AtUri<S>>,
        Option<AtUri<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> MultiObservation<S> {
    /// Create a new builder for this type
    pub fn builder() -> MultiObservationBuilder<multi_observation_state::Empty, S> {
        MultiObservationBuilder::builder()
    }
}

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

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

impl<St: multi_observation_state::State, S: BosStr> MultiObservationBuilder<St, S> {
    /// Set the `derivedFrom` field (optional)
    pub fn derived_from(mut self, value: impl Into<Option<Vec<AtUri<S>>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `derivedFrom` field to an Option value (optional)
    pub fn maybe_derived_from(mut self, value: Option<Vec<AtUri<S>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> MultiObservationBuilder<St, S>
where
    St: multi_observation_state::State,
    St::Entries: multi_observation_state::IsUnset,
{
    /// Set the `entries` field (required)
    pub fn entries(
        mut self,
        value: impl Into<Vec<multi_observation::MultiObservationEntry<S>>>,
    ) -> MultiObservationBuilder<multi_observation_state::SetEntries<St>, S> {
        self._fields.1 = Option::Some(value.into());
        MultiObservationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> MultiObservationBuilder<St, S>
where
    St: multi_observation_state::State,
    St::PhenomenonTime: multi_observation_state::IsUnset,
{
    /// Set the `phenomenonTime` field (required)
    pub fn phenomenon_time(
        mut self,
        value: impl Into<Datetime>,
    ) -> MultiObservationBuilder<multi_observation_state::SetPhenomenonTime<St>, S> {
        self._fields.2 = Option::Some(value.into());
        MultiObservationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: multi_observation_state::State, S: BosStr> MultiObservationBuilder<St, S> {
    /// Set the `phenomenonTimeEnd` field (optional)
    pub fn phenomenon_time_end(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `phenomenonTimeEnd` field to an Option value (optional)
    pub fn maybe_phenomenon_time_end(mut self, value: Option<Datetime>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: multi_observation_state::State, S: BosStr> MultiObservationBuilder<St, S> {
    /// Set the `resultQuality` field (optional)
    pub fn result_quality(
        mut self,
        value: impl Into<Option<MultiObservationResultQuality<S>>>,
    ) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `resultQuality` field to an Option value (optional)
    pub fn maybe_result_quality(
        mut self,
        value: Option<MultiObservationResultQuality<S>>,
    ) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: multi_observation_state::State, S: BosStr> MultiObservationBuilder<St, S> {
    /// Set the `resultTime` field (optional)
    pub fn result_time(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `resultTime` field to an Option value (optional)
    pub fn maybe_result_time(mut self, value: Option<Datetime>) -> Self {
        self._fields.5 = value;
        self
    }
}

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

impl<St, S: BosStr> MultiObservationBuilder<St, S>
where
    St: multi_observation_state::State,
    St::Thing: multi_observation_state::IsUnset,
{
    /// Set the `thing` field (required)
    pub fn thing(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> MultiObservationBuilder<multi_observation_state::SetThing<St>, S> {
        self._fields.7 = Option::Some(value.into());
        MultiObservationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> MultiObservationBuilder<St, S>
where
    St: multi_observation_state::State,
    St::Entries: multi_observation_state::IsSet,
    St::PhenomenonTime: multi_observation_state::IsSet,
    St::Sensor: multi_observation_state::IsSet,
    St::Thing: multi_observation_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> MultiObservation<S> {
        MultiObservation {
            derived_from: self._fields.0,
            entries: self._fields.1.unwrap(),
            phenomenon_time: self._fields.2.unwrap(),
            phenomenon_time_end: self._fields.3,
            result_quality: self._fields.4,
            result_time: self._fields.5,
            sensor: self._fields.6.unwrap(),
            thing: self._fields.7.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> MultiObservation<S> {
        MultiObservation {
            derived_from: self._fields.0,
            entries: self._fields.1.unwrap(),
            phenomenon_time: self._fields.2.unwrap(),
            phenomenon_time_end: self._fields.3,
            result_quality: self._fields.4,
            result_time: self._fields.5,
            sensor: self._fields.6.unwrap(),
            thing: self._fields.7.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_dev_sensorthings_multiObservation() -> 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.sensorthings.multiObservation"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A composite observation bundling multiple co-produced results from a single act of sensing. Each entry carries its own ObservedProperty, unit, and scale metadata. Use this instead of separate Observations when the results are genuinely co-produced (e.g. wave statistics from spectral processing) and have no independent existence.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("thing"), SmolStr::new_static("sensor"),
                                SmolStr::new_static("phenomenonTime"),
                                SmolStr::new_static("entries")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("derivedFrom"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT-URIs of source observations or datastreams",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                    max_length: Some(16usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("entries"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Array of co-produced result entries"),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#multiObservationEntry"),
                                        ..Default::default()
                                    }),
                                    max_length: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("phenomenonTime"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Time the phenomenon was observed. Start of interval if phenomenonTimeEnd is present.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("phenomenonTimeEnd"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "End of observation interval. For wave statistics, this is the end of the burst window.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("resultQuality"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Quality flag applying to the composite observation as a whole",
                                        ),
                                    ),
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("resultTime"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Time the results became available"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("sensor"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT-URI of the dev.sensorthings.sensor record (the instrument or process that co-produced these results)",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("thing"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT-URI of the dev.sensorthings.thing record",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("multiObservationEntry"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A single result within a composite observation, fully self-describing.",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("observedProperty"),
                            SmolStr::new_static("unitOfMeasurement"),
                            SmolStr::new_static("result")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("observedProperty"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "AT-URI of the dev.sensorthings.observedProperty record",
                                    ),
                                ),
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("result"),
                            LexObjectProperty::Union(LexRefUnion {
                                refs: vec![
                                    CowStr::new_static("dev.sensorthings.observation#numericResult"),
                                    CowStr::new_static("dev.sensorthings.observation#categoryResult"),
                                    CowStr::new_static("dev.sensorthings.observation#booleanResult"),
                                    CowStr::new_static("dev.sensorthings.observation#arrayResult"),
                                    CowStr::new_static("dev.sensorthings.observation#geoPointResult")
                                ],
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("resultQuality"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Quality flag for this specific entry, if different from the composite quality",
                                    ),
                                ),
                                max_length: Some(64usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("resultScaleFactor"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("unitOfMeasurement"),
                            LexObjectProperty::Ref(LexRef {
                                r#ref: CowStr::new_static(
                                    "dev.sensorthings.datastream#unitOfMeasurement",
                                ),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod multi_observation_entry_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 ObservedProperty;
        type Result;
        type UnitOfMeasurement;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type ObservedProperty = Unset;
        type Result = Unset;
        type UnitOfMeasurement = Unset;
    }
    ///State transition - sets the `observed_property` field to Set
    pub struct SetObservedProperty<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetObservedProperty<St> {}
    impl<St: State> State for SetObservedProperty<St> {
        type ObservedProperty = Set<members::observed_property>;
        type Result = St::Result;
        type UnitOfMeasurement = St::UnitOfMeasurement;
    }
    ///State transition - sets the `result` field to Set
    pub struct SetResult<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetResult<St> {}
    impl<St: State> State for SetResult<St> {
        type ObservedProperty = St::ObservedProperty;
        type Result = Set<members::result>;
        type UnitOfMeasurement = St::UnitOfMeasurement;
    }
    ///State transition - sets the `unit_of_measurement` field to Set
    pub struct SetUnitOfMeasurement<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetUnitOfMeasurement<St> {}
    impl<St: State> State for SetUnitOfMeasurement<St> {
        type ObservedProperty = St::ObservedProperty;
        type Result = St::Result;
        type UnitOfMeasurement = Set<members::unit_of_measurement>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `observed_property` field
        pub struct observed_property(());
        ///Marker type for the `result` field
        pub struct result(());
        ///Marker type for the `unit_of_measurement` field
        pub struct unit_of_measurement(());
    }
}

/// Builder for constructing an instance of this type.
pub struct MultiObservationEntryBuilder<
    St: multi_observation_entry_state::State,
    S: BosStr = DefaultStr,
> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<AtUri<S>>,
        Option<MultiObservationEntryResult<S>>,
        Option<MultiObservationEntryResultQuality<S>>,
        Option<i64>,
        Option<UnitOfMeasurement<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> MultiObservationEntry<S> {
    /// Create a new builder for this type
    pub fn builder() -> MultiObservationEntryBuilder<
        multi_observation_entry_state::Empty,
        S,
    > {
        MultiObservationEntryBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> MultiObservationEntryBuilder<St, S>
where
    St: multi_observation_entry_state::State,
    St::ObservedProperty: multi_observation_entry_state::IsUnset,
{
    /// Set the `observedProperty` field (required)
    pub fn observed_property(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> MultiObservationEntryBuilder<
        multi_observation_entry_state::SetObservedProperty<St>,
        S,
    > {
        self._fields.0 = Option::Some(value.into());
        MultiObservationEntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> MultiObservationEntryBuilder<St, S>
where
    St: multi_observation_entry_state::State,
    St::Result: multi_observation_entry_state::IsUnset,
{
    /// Set the `result` field (required)
    pub fn result(
        mut self,
        value: impl Into<MultiObservationEntryResult<S>>,
    ) -> MultiObservationEntryBuilder<multi_observation_entry_state::SetResult<St>, S> {
        self._fields.1 = Option::Some(value.into());
        MultiObservationEntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<
    St: multi_observation_entry_state::State,
    S: BosStr,
> MultiObservationEntryBuilder<St, S> {
    /// Set the `resultQuality` field (optional)
    pub fn result_quality(
        mut self,
        value: impl Into<Option<MultiObservationEntryResultQuality<S>>>,
    ) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `resultQuality` field to an Option value (optional)
    pub fn maybe_result_quality(
        mut self,
        value: Option<MultiObservationEntryResultQuality<S>>,
    ) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<
    St: multi_observation_entry_state::State,
    S: BosStr,
> MultiObservationEntryBuilder<St, S> {
    /// Set the `resultScaleFactor` field (optional)
    pub fn result_scale_factor(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `resultScaleFactor` field to an Option value (optional)
    pub fn maybe_result_scale_factor(mut self, value: Option<i64>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> MultiObservationEntryBuilder<St, S>
where
    St: multi_observation_entry_state::State,
    St::UnitOfMeasurement: multi_observation_entry_state::IsUnset,
{
    /// Set the `unitOfMeasurement` field (required)
    pub fn unit_of_measurement(
        mut self,
        value: impl Into<UnitOfMeasurement<S>>,
    ) -> MultiObservationEntryBuilder<
        multi_observation_entry_state::SetUnitOfMeasurement<St>,
        S,
    > {
        self._fields.4 = Option::Some(value.into());
        MultiObservationEntryBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> MultiObservationEntryBuilder<St, S>
where
    St: multi_observation_entry_state::State,
    St::ObservedProperty: multi_observation_entry_state::IsSet,
    St::Result: multi_observation_entry_state::IsSet,
    St::UnitOfMeasurement: multi_observation_entry_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> MultiObservationEntry<S> {
        MultiObservationEntry {
            observed_property: self._fields.0.unwrap(),
            result: self._fields.1.unwrap(),
            result_quality: self._fields.2,
            result_scale_factor: self._fields.3,
            unit_of_measurement: self._fields.4.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>>,
    ) -> MultiObservationEntry<S> {
        MultiObservationEntry {
            observed_property: self._fields.0.unwrap(),
            result: self._fields.1.unwrap(),
            result_quality: self._fields.2,
            result_scale_factor: self._fields.3,
            unit_of_measurement: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}