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

#[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};
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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct CodeHash<'a> {
    ///Hash algorithm identifier (e.g., 'sha256', 'blake3')
    #[serde(borrow)]
    pub algorithm: CowStr<'a>,
    ///Hex-encoded hash digest
    #[serde(borrow)]
    pub digest: CowStr<'a>,
}

/// 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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct LensVerification<'a> {
    ///Hash of the code at the referenced commit. Required for signedHash method.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub code_hash: Option<lens_verification::CodeHash<'a>>,
    ///Timestamp when this verification was issued
    pub created_at: Datetime,
    ///Human-readable description of what was verified
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub description: Option<CowStr<'a>>,
    ///AT-URI of the lens record being verified
    #[serde(borrow)]
    pub lens: AtUri<'a>,
    ///CID of the specific lens record version. Ensures immutability — if the lens is updated, old verifications do not carry over.
    #[serde(borrow)]
    pub lens_commit: CowStr<'a>,
    ///Link to proof artifact (Coq/Lean proof, test suite, etc.). Used with formalProof or automatedTest methods.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub proof_ref: Option<CodeReference<'a>>,
    ///What kind of verification was performed
    #[serde(borrow)]
    pub verification_method: VerificationMethod<'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 LensVerificationGetRecordOutput<'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: LensVerification<'a>,
}

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

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

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

impl Collection for LensVerification<'_> {
    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<'a> LexiconSchema for LensVerification<'a> {
    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 VerificationMethod;
        type CreatedAt;
        type Lens;
        type LensCommit;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type VerificationMethod = Unset;
        type CreatedAt = Unset;
        type Lens = Unset;
        type LensCommit = Unset;
    }
    ///State transition - sets the `verification_method` field to Set
    pub struct SetVerificationMethod<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetVerificationMethod<S> {}
    impl<S: State> State for SetVerificationMethod<S> {
        type VerificationMethod = Set<members::verification_method>;
        type CreatedAt = S::CreatedAt;
        type Lens = S::Lens;
        type LensCommit = S::LensCommit;
    }
    ///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 VerificationMethod = S::VerificationMethod;
        type CreatedAt = Set<members::created_at>;
        type Lens = S::Lens;
        type LensCommit = S::LensCommit;
    }
    ///State transition - sets the `lens` field to Set
    pub struct SetLens<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetLens<S> {}
    impl<S: State> State for SetLens<S> {
        type VerificationMethod = S::VerificationMethod;
        type CreatedAt = S::CreatedAt;
        type Lens = Set<members::lens>;
        type LensCommit = S::LensCommit;
    }
    ///State transition - sets the `lens_commit` field to Set
    pub struct SetLensCommit<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetLensCommit<S> {}
    impl<S: State> State for SetLensCommit<S> {
        type VerificationMethod = S::VerificationMethod;
        type CreatedAt = S::CreatedAt;
        type Lens = S::Lens;
        type LensCommit = Set<members::lens_commit>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `verification_method` field
        pub struct verification_method(());
        ///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(());
    }
}

/// Builder for constructing an instance of this type
pub struct LensVerificationBuilder<'a, S: lens_verification_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<lens_verification::CodeHash<'a>>,
        Option<Datetime>,
        Option<CowStr<'a>>,
        Option<AtUri<'a>>,
        Option<CowStr<'a>>,
        Option<CodeReference<'a>>,
        Option<VerificationMethod<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

impl<'a, S: lens_verification_state::State> LensVerificationBuilder<'a, S> {
    /// Set the `codeHash` field (optional)
    pub fn code_hash(
        mut self,
        value: impl Into<Option<lens_verification::CodeHash<'a>>>,
    ) -> 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<'a>>,
    ) -> Self {
        self._fields.0 = value;
        self
    }
}

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

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

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

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

impl<'a, S: lens_verification_state::State> LensVerificationBuilder<'a, S> {
    /// Set the `proofRef` field (optional)
    pub fn proof_ref(mut self, value: impl Into<Option<CodeReference<'a>>>) -> 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<'a>>) -> Self {
        self._fields.5 = value;
        self
    }
}

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

impl<'a, S> LensVerificationBuilder<'a, S>
where
    S: lens_verification_state::State,
    S::VerificationMethod: lens_verification_state::IsSet,
    S::CreatedAt: lens_verification_state::IsSet,
    S::Lens: lens_verification_state::IsSet,
    S::LensCommit: lens_verification_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> LensVerification<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> LensVerification<'a> {
        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),
        }
    }
}