// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.gainforest.evaluator.evaluation
//
// 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::app_gainforest::evaluator::ClassificationResult;
use crate::app_gainforest::evaluator::DataQualityResult;
use crate::app_gainforest::evaluator::MeasurementResult;
use crate::app_gainforest::evaluator::MethodInfo;
use crate::app_gainforest::evaluator::SpeciesIdResult;
use crate::app_gainforest::evaluator::SubjectRef;
use crate::app_gainforest::evaluator::VerificationResult;
/// A single evaluation produced by an evaluator service. Exactly one of 'subject' (single target) or 'subjects' (batch) must be provided.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.gainforest.evaluator.evaluation",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Evaluation<S: BosStr = DefaultStr> {
    ///Overall confidence in this evaluation (0-1000, where 1000 = 100.0%).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<i64>,
    ///Timestamp of when this evaluation was produced.
    pub created_at: Datetime,
    ///Additional structured data as a JSON string. Escape hatch for experimental result types before they are formalized into the union.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dynamic_properties: Option<S>,
    ///Identifier for the type of evaluation (must match one declared in the evaluator's service record).
    pub evaluation_type: S,
    ///Method/model provenance for this specific evaluation (overrides service-level method if set).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<MethodInfo<S>>,
    ///If true, this is a negation/withdrawal of a previous evaluation (like label negation).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub neg: Option<bool>,
    ///The typed evaluation result. The $type field determines which result schema is used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<EvaluationResult<S>>,
    ///Single target record being evaluated. Use this OR subjects, not both.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<SubjectRef<S>>,
    ///Batch evaluation: multiple target records sharing the same result. Use this OR subject, not both.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subjects: Option<Vec<SubjectRef<S>>>,
    ///AT-URI of a previous evaluation record that this one supersedes (e.g., model re-run with improved version).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supersedes: Option<AtUri<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum EvaluationResult<S: BosStr = DefaultStr> {
    #[serde(rename = "app.gainforest.evaluator.defs#speciesIdResult")]
    SpeciesIdResult(Box<SpeciesIdResult<S>>),
    #[serde(rename = "app.gainforest.evaluator.defs#dataQualityResult")]
    DataQualityResult(Box<DataQualityResult<S>>),
    #[serde(rename = "app.gainforest.evaluator.defs#verificationResult")]
    VerificationResult(Box<VerificationResult<S>>),
    #[serde(rename = "app.gainforest.evaluator.defs#classificationResult")]
    ClassificationResult(Box<ClassificationResult<S>>),
    #[serde(rename = "app.gainforest.evaluator.defs#measurementResult")]
    MeasurementResult(Box<MeasurementResult<S>>),
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct EvaluationGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Evaluation<S>,
}

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

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

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

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

impl<S: BosStr> Collection for Evaluation<S> {
    const NSID: &'static str = "app.gainforest.evaluator.evaluation";
    type Record = EvaluationRecord;
}

impl Collection for EvaluationRecord {
    const NSID: &'static str = "app.gainforest.evaluator.evaluation";
    type Record = EvaluationRecord;
}

impl<S: BosStr> LexiconSchema for Evaluation<S> {
    fn nsid() -> &'static str {
        "app.gainforest.evaluator.evaluation"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_gainforest_evaluator_evaluation()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.confidence {
            if *value > 1000i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("confidence"),
                    max: 1000i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.confidence {
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("confidence"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        if let Some(ref value) = self.dynamic_properties {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 10000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("dynamic_properties"),
                        max: 10000usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.evaluation_type;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 64usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("evaluation_type"),
                        max: 64usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.subjects {
            #[allow(unused_comparisons)]
            if value.len() > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("subjects"),
                    max: 100usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

pub mod evaluation_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 EvaluationType;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type EvaluationType = 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 EvaluationType = St::EvaluationType;
    }
    ///State transition - sets the `evaluation_type` field to Set
    pub struct SetEvaluationType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetEvaluationType<St> {}
    impl<St: State> State for SetEvaluationType<St> {
        type CreatedAt = St::CreatedAt;
        type EvaluationType = Set<members::evaluation_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 `evaluation_type` field
        pub struct evaluation_type(());
    }
}

/// Builder for constructing an instance of this type.
pub struct EvaluationBuilder<St: evaluation_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<i64>,
        Option<Datetime>,
        Option<S>,
        Option<S>,
        Option<MethodInfo<S>>,
        Option<bool>,
        Option<EvaluationResult<S>>,
        Option<SubjectRef<S>>,
        Option<Vec<SubjectRef<S>>>,
        Option<AtUri<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Evaluation<S> {
    /// Create a new builder for this type
    pub fn builder() -> EvaluationBuilder<evaluation_state::Empty, S> {
        EvaluationBuilder::builder()
    }
}

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

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

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

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

impl<St: evaluation_state::State, S: BosStr> EvaluationBuilder<St, S> {
    /// Set the `dynamicProperties` field (optional)
    pub fn dynamic_properties(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `dynamicProperties` field to an Option value (optional)
    pub fn maybe_dynamic_properties(mut self, value: Option<S>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> EvaluationBuilder<St, S>
where
    St: evaluation_state::State,
    St::EvaluationType: evaluation_state::IsUnset,
{
    /// Set the `evaluationType` field (required)
    pub fn evaluation_type(
        mut self,
        value: impl Into<S>,
    ) -> EvaluationBuilder<evaluation_state::SetEvaluationType<St>, S> {
        self._fields.3 = Option::Some(value.into());
        EvaluationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: evaluation_state::State, S: BosStr> EvaluationBuilder<St, S> {
    /// Set the `method` field (optional)
    pub fn method(mut self, value: impl Into<Option<MethodInfo<S>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `method` field to an Option value (optional)
    pub fn maybe_method(mut self, value: Option<MethodInfo<S>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: evaluation_state::State, S: BosStr> EvaluationBuilder<St, S> {
    /// Set the `neg` field (optional)
    pub fn neg(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `neg` field to an Option value (optional)
    pub fn maybe_neg(mut self, value: Option<bool>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St: evaluation_state::State, S: BosStr> EvaluationBuilder<St, S> {
    /// Set the `result` field (optional)
    pub fn result(mut self, value: impl Into<Option<EvaluationResult<S>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `result` field to an Option value (optional)
    pub fn maybe_result(mut self, value: Option<EvaluationResult<S>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St: evaluation_state::State, S: BosStr> EvaluationBuilder<St, S> {
    /// Set the `subject` field (optional)
    pub fn subject(mut self, value: impl Into<Option<SubjectRef<S>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `subject` field to an Option value (optional)
    pub fn maybe_subject(mut self, value: Option<SubjectRef<S>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St: evaluation_state::State, S: BosStr> EvaluationBuilder<St, S> {
    /// Set the `subjects` field (optional)
    pub fn subjects(mut self, value: impl Into<Option<Vec<SubjectRef<S>>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `subjects` field to an Option value (optional)
    pub fn maybe_subjects(mut self, value: Option<Vec<SubjectRef<S>>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<St: evaluation_state::State, S: BosStr> EvaluationBuilder<St, S> {
    /// Set the `supersedes` field (optional)
    pub fn supersedes(mut self, value: impl Into<Option<AtUri<S>>>) -> Self {
        self._fields.9 = value.into();
        self
    }
    /// Set the `supersedes` field to an Option value (optional)
    pub fn maybe_supersedes(mut self, value: Option<AtUri<S>>) -> Self {
        self._fields.9 = value;
        self
    }
}

impl<St, S: BosStr> EvaluationBuilder<St, S>
where
    St: evaluation_state::State,
    St::CreatedAt: evaluation_state::IsSet,
    St::EvaluationType: evaluation_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Evaluation<S> {
        Evaluation {
            confidence: self._fields.0,
            created_at: self._fields.1.unwrap(),
            dynamic_properties: self._fields.2,
            evaluation_type: self._fields.3.unwrap(),
            method: self._fields.4,
            neg: self._fields.5,
            result: self._fields.6,
            subject: self._fields.7,
            subjects: self._fields.8,
            supersedes: self._fields.9,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Evaluation<S> {
        Evaluation {
            confidence: self._fields.0,
            created_at: self._fields.1.unwrap(),
            dynamic_properties: self._fields.2,
            evaluation_type: self._fields.3.unwrap(),
            method: self._fields.4,
            neg: self._fields.5,
            result: self._fields.6,
            subject: self._fields.7,
            subjects: self._fields.8,
            supersedes: self._fields.9,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_gainforest_evaluator_evaluation() -> 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.gainforest.evaluator.evaluation"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A single evaluation produced by an evaluator service. Exactly one of 'subject' (single target) or 'subjects' (batch) must be provided.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("evaluationType"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("confidence"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    maximum: Some(1000i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp of when this evaluation was produced.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("dynamicProperties"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Additional structured data as a JSON string. Escape hatch for experimental result types before they are formalized into the union.",
                                        ),
                                    ),
                                    max_graphemes: Some(10000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("evaluationType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Identifier for the type of evaluation (must match one declared in the evaluator's service record).",
                                        ),
                                    ),
                                    max_graphemes: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("method"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "app.gainforest.evaluator.defs#methodInfo",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("neg"),
                                LexObjectProperty::Boolean(LexBoolean {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("result"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "The typed evaluation result. The $type field determines which result schema is used.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("app.gainforest.evaluator.defs#speciesIdResult"),
                                        CowStr::new_static("app.gainforest.evaluator.defs#dataQualityResult"),
                                        CowStr::new_static("app.gainforest.evaluator.defs#verificationResult"),
                                        CowStr::new_static("app.gainforest.evaluator.defs#classificationResult"),
                                        CowStr::new_static("app.gainforest.evaluator.defs#measurementResult")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subject"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "app.gainforest.evaluator.defs#subjectRef",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("subjects"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Batch evaluation: multiple target records sharing the same result. Use this OR subject, not both.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static(
                                            "app.gainforest.evaluator.defs#subjectRef",
                                        ),
                                        ..Default::default()
                                    }),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("supersedes"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT-URI of a previous evaluation record that this one supersedes (e.g., model re-run with improved version).",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}