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

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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, 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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Evaluation<'a> {
    ///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")]
    #[serde(borrow)]
    pub dynamic_properties: Option<CowStr<'a>>,
    ///Identifier for the type of evaluation (must match one declared in the evaluator's service record).
    #[serde(borrow)]
    pub evaluation_type: CowStr<'a>,
    ///Method/model provenance for this specific evaluation (overrides service-level method if set).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub method: Option<MethodInfo<'a>>,
    ///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")]
    #[serde(borrow)]
    pub result: Option<EvaluationResult<'a>>,
    ///Single target record being evaluated. Use this OR subjects, not both.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub subject: Option<SubjectRef<'a>>,
    ///Batch evaluation: multiple target records sharing the same result. Use this OR subject, not both.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub subjects: Option<Vec<SubjectRef<'a>>>,
    ///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")]
    #[serde(borrow)]
    pub supersedes: Option<AtUri<'a>>,
}


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

/// 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<'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: Evaluation<'a>,
}

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

/// 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<'de> = EvaluationGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Evaluation<'_> {
    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<'a> LexiconSchema for Evaluation<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        type CreatedAt = Set<members::created_at>;
        type EvaluationType = S::EvaluationType;
    }
    ///State transition - sets the `evaluation_type` field to Set
    pub struct SetEvaluationType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetEvaluationType<S> {}
    impl<S: State> State for SetEvaluationType<S> {
        type CreatedAt = S::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<'a, S: evaluation_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<i64>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<CowStr<'a>>,
        Option<MethodInfo<'a>>,
        Option<bool>,
        Option<EvaluationResult<'a>>,
        Option<SubjectRef<'a>>,
        Option<Vec<SubjectRef<'a>>>,
        Option<AtUri<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

impl<'a, S: evaluation_state::State> EvaluationBuilder<'a, 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<'a, S> EvaluationBuilder<'a, S>
where
    S: evaluation_state::State,
    S::CreatedAt: evaluation_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> EvaluationBuilder<'a, evaluation_state::SetCreatedAt<S>> {
        self._fields.1 = Option::Some(value.into());
        EvaluationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: evaluation_state::State> EvaluationBuilder<'a, S> {
    /// Set the `dynamicProperties` field (optional)
    pub fn dynamic_properties(mut self, value: impl Into<Option<CowStr<'a>>>) -> 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<CowStr<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

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

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

impl<'a, S: evaluation_state::State> EvaluationBuilder<'a, 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<'a, S: evaluation_state::State> EvaluationBuilder<'a, S> {
    /// Set the `result` field (optional)
    pub fn result(mut self, value: impl Into<Option<EvaluationResult<'a>>>) -> 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<'a>>) -> Self {
        self._fields.6 = value;
        self
    }
}

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

impl<'a, S: evaluation_state::State> EvaluationBuilder<'a, S> {
    /// Set the `subjects` field (optional)
    pub fn subjects(mut self, value: impl Into<Option<Vec<SubjectRef<'a>>>>) -> 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<'a>>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S: evaluation_state::State> EvaluationBuilder<'a, S> {
    /// Set the `supersedes` field (optional)
    pub fn supersedes(mut self, value: impl Into<Option<AtUri<'a>>>) -> 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<'a>>) -> Self {
        self._fields.9 = value;
        self
    }
}

impl<'a, S> EvaluationBuilder<'a, S>
where
    S: evaluation_state::State,
    S::CreatedAt: evaluation_state::IsSet,
    S::EvaluationType: evaluation_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Evaluation<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Evaluation<'a> {
        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()
    }
}