// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: science.alt.dataset.lensVerification
//
// 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};
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::science_alt::dataset::lens::CodeReference;
use crate::science_alt::dataset::verification_method::VerificationMethod;
use crate::science_alt::dataset::lens_verification;
/// Content hash for code integrity verification

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CodeHash<S: BosStr = DefaultStr> {
    ///Hash algorithm identifier (e.g., 'sha256', 'blake3')
    pub algorithm: S,
    ///Hex-encoded hash digest
    pub digest: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Verification record for a lens transformation. The verifier's identity is implicit — the DID of the repo owner who writes this record. Follows the ATProto pattern where verification records live in the verifier's own PDS.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "science.alt.dataset.lensVerification",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct LensVerification<S: BosStr = DefaultStr> {
    ///Hash of the code at the referenced commit. Required for signedHash method.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_hash: Option<lens_verification::CodeHash<S>>,
    ///Timestamp when this verification was issued
    pub created_at: Datetime,
    ///Human-readable description of what was verified
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///AT-URI of the lens record being verified
    pub lens: AtUri<S>,
    ///CID of the specific lens record version. Ensures immutability — if the lens is updated, old verifications do not carry over.
    pub lens_commit: S,
    ///Link to proof artifact (Coq/Lean proof, test suite, etc.). Used with formalProof or automatedTest methods.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proof_ref: Option<CodeReference<S>>,
    ///What kind of verification was performed
    pub verification_method: VerificationMethod<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<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 LensVerificationGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: LensVerification<S>,
}

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

impl<S: BosStr> LexiconSchema for CodeHash<S> {
    fn nsid() -> &'static str {
        "science.alt.dataset.lensVerification"
    }
    fn def_name() -> &'static str {
        "codeHash"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_science_alt_dataset_lensVerification()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.algorithm;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("algorithm"),
                    max: 20usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.digest;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("digest"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct LensVerificationRecord;
impl XrpcResp for LensVerificationRecord {
    const NSID: &'static str = "science.alt.dataset.lensVerification";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = LensVerificationGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for LensVerification<S> {
    const NSID: &'static str = "science.alt.dataset.lensVerification";
    type Record = LensVerificationRecord;
}

impl Collection for LensVerificationRecord {
    const NSID: &'static str = "science.alt.dataset.lensVerification";
    type Record = LensVerificationRecord;
}

impl<S: BosStr> LexiconSchema for LensVerification<S> {
    fn nsid() -> &'static str {
        "science.alt.dataset.lensVerification"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_science_alt_dataset_lensVerification()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.lens;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 500usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("lens"),
                    max: 500usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.lens_commit;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("lens_commit"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

fn lexicon_doc_science_alt_dataset_lensVerification() -> 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("science.alt.dataset.lensVerification"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("codeHash"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Content hash for code integrity verification",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("algorithm"),
                            SmolStr::new_static("digest")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("algorithm"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Hash algorithm identifier (e.g., 'sha256', 'blake3')",
                                    ),
                                ),
                                max_length: Some(20usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("digest"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Hex-encoded hash digest"),
                                ),
                                max_length: Some(128usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Verification record for a lens transformation. The verifier's identity is implicit — the DID of the repo owner who writes this record. Follows the ATProto pattern where verification records live in the verifier's own PDS.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("lens"),
                                SmolStr::new_static("lensCommit"),
                                SmolStr::new_static("verificationMethod"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("codeHash"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#codeHash"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Timestamp when this verification was issued",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Human-readable description of what was verified",
                                        ),
                                    ),
                                    max_length: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("lens"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "AT-URI of the lens record being verified",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    max_length: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("lensCommit"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "CID of the specific lens record version. Ensures immutability — if the lens is updated, old verifications do not carry over.",
                                        ),
                                    ),
                                    max_length: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("proofRef"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "science.alt.dataset.lens#codeReference",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("verificationMethod"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "science.alt.dataset.verificationMethod",
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod lens_verification_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 Lens;
        type LensCommit;
        type VerificationMethod;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type Lens = Unset;
        type LensCommit = Unset;
        type VerificationMethod = 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 Lens = St::Lens;
        type LensCommit = St::LensCommit;
        type VerificationMethod = St::VerificationMethod;
    }
    ///State transition - sets the `lens` field to Set
    pub struct SetLens<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLens<St> {}
    impl<St: State> State for SetLens<St> {
        type CreatedAt = St::CreatedAt;
        type Lens = Set<members::lens>;
        type LensCommit = St::LensCommit;
        type VerificationMethod = St::VerificationMethod;
    }
    ///State transition - sets the `lens_commit` field to Set
    pub struct SetLensCommit<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLensCommit<St> {}
    impl<St: State> State for SetLensCommit<St> {
        type CreatedAt = St::CreatedAt;
        type Lens = St::Lens;
        type LensCommit = Set<members::lens_commit>;
        type VerificationMethod = St::VerificationMethod;
    }
    ///State transition - sets the `verification_method` field to Set
    pub struct SetVerificationMethod<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetVerificationMethod<St> {}
    impl<St: State> State for SetVerificationMethod<St> {
        type CreatedAt = St::CreatedAt;
        type Lens = St::Lens;
        type LensCommit = St::LensCommit;
        type VerificationMethod = Set<members::verification_method>;
    }
    /// 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 `lens` field
        pub struct lens(());
        ///Marker type for the `lens_commit` field
        pub struct lens_commit(());
        ///Marker type for the `verification_method` field
        pub struct verification_method(());
    }
}

/// Builder for constructing an instance of this type.
pub struct LensVerificationBuilder<
    St: lens_verification_state::State,
    S: BosStr = DefaultStr,
> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<lens_verification::CodeHash<S>>,
        Option<Datetime>,
        Option<S>,
        Option<AtUri<S>>,
        Option<S>,
        Option<CodeReference<S>>,
        Option<VerificationMethod<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> LensVerification<S> {
    /// Create a new builder for this type
    pub fn builder() -> LensVerificationBuilder<lens_verification_state::Empty, S> {
        LensVerificationBuilder::builder()
    }
}

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

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

impl<St: lens_verification_state::State, S: BosStr> LensVerificationBuilder<St, S> {
    /// Set the `codeHash` field (optional)
    pub fn code_hash(
        mut self,
        value: impl Into<Option<lens_verification::CodeHash<S>>>,
    ) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `codeHash` field to an Option value (optional)
    pub fn maybe_code_hash(
        mut self,
        value: Option<lens_verification::CodeHash<S>>,
    ) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

impl<St, S: BosStr> LensVerificationBuilder<St, S>
where
    St: lens_verification_state::State,
    St::Lens: lens_verification_state::IsUnset,
{
    /// Set the `lens` field (required)
    pub fn lens(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> LensVerificationBuilder<lens_verification_state::SetLens<St>, S> {
        self._fields.3 = Option::Some(value.into());
        LensVerificationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LensVerificationBuilder<St, S>
where
    St: lens_verification_state::State,
    St::LensCommit: lens_verification_state::IsUnset,
{
    /// Set the `lensCommit` field (required)
    pub fn lens_commit(
        mut self,
        value: impl Into<S>,
    ) -> LensVerificationBuilder<lens_verification_state::SetLensCommit<St>, S> {
        self._fields.4 = Option::Some(value.into());
        LensVerificationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: lens_verification_state::State, S: BosStr> LensVerificationBuilder<St, S> {
    /// Set the `proofRef` field (optional)
    pub fn proof_ref(mut self, value: impl Into<Option<CodeReference<S>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `proofRef` field to an Option value (optional)
    pub fn maybe_proof_ref(mut self, value: Option<CodeReference<S>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St, S: BosStr> LensVerificationBuilder<St, S>
where
    St: lens_verification_state::State,
    St::VerificationMethod: lens_verification_state::IsUnset,
{
    /// Set the `verificationMethod` field (required)
    pub fn verification_method(
        mut self,
        value: impl Into<VerificationMethod<S>>,
    ) -> LensVerificationBuilder<lens_verification_state::SetVerificationMethod<St>, S> {
        self._fields.6 = Option::Some(value.into());
        LensVerificationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LensVerificationBuilder<St, S>
where
    St: lens_verification_state::State,
    St::CreatedAt: lens_verification_state::IsSet,
    St::Lens: lens_verification_state::IsSet,
    St::LensCommit: lens_verification_state::IsSet,
    St::VerificationMethod: lens_verification_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> LensVerification<S> {
        LensVerification {
            code_hash: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            lens: self._fields.3.unwrap(),
            lens_commit: self._fields.4.unwrap(),
            proof_ref: self._fields.5,
            verification_method: self._fields.6.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>>,
    ) -> LensVerification<S> {
        LensVerification {
            code_hash: self._fields.0,
            created_at: self._fields.1.unwrap(),
            description: self._fields.2,
            lens: self._fields.3.unwrap(),
            lens_commit: self._fields.4.unwrap(),
            proof_ref: self._fields.5,
            verification_method: self._fields.6.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}