// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: io.atcr.hold.stats
//
// 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::{Did, 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};
/// Repository statistics stored in the hold's embedded PDS. Tracks pull/push counts per owner+repository combination. Record key is deterministic: base32(sha256(ownerDID + "/" + repository)[:16]).

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Stats<'a> {
    ///RFC3339 timestamp of last pull
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_pull: Option<Datetime>,
    ///RFC3339 timestamp of last push
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_push: Option<Datetime>,
    ///DID of the image owner (e.g., did:plc:xyz123)
    #[serde(borrow)]
    pub owner_did: Did<'a>,
    ///Number of manifest downloads
    pub pull_count: i64,
    ///Number of manifest uploads
    pub push_count: i64,
    ///Repository name (e.g., myapp)
    #[serde(borrow)]
    pub repository: CowStr<'a>,
    ///RFC3339 timestamp of when this record was last updated
    pub updated_at: Datetime,
}

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

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct StatsRecord;
impl XrpcResp for StatsRecord {
    const NSID: &'static str = "io.atcr.hold.stats";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = StatsGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Stats<'_> {
    const NSID: &'static str = "io.atcr.hold.stats";
    type Record = StatsRecord;
}

impl Collection for StatsRecord {
    const NSID: &'static str = "io.atcr.hold.stats";
    type Record = StatsRecord;
}

impl<'a> LexiconSchema for Stats<'a> {
    fn nsid() -> &'static str {
        "io.atcr.hold.stats"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_io_atcr_hold_stats()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.pull_count;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("pull_count"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.push_count;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("push_count"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.repository;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 256usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("repository"),
                    max: 256usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod stats_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 PushCount;
        type UpdatedAt;
        type Repository;
        type PullCount;
        type OwnerDid;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type PushCount = Unset;
        type UpdatedAt = Unset;
        type Repository = Unset;
        type PullCount = Unset;
        type OwnerDid = Unset;
    }
    ///State transition - sets the `push_count` field to Set
    pub struct SetPushCount<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPushCount<S> {}
    impl<S: State> State for SetPushCount<S> {
        type PushCount = Set<members::push_count>;
        type UpdatedAt = S::UpdatedAt;
        type Repository = S::Repository;
        type PullCount = S::PullCount;
        type OwnerDid = S::OwnerDid;
    }
    ///State transition - sets the `updated_at` field to Set
    pub struct SetUpdatedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUpdatedAt<S> {}
    impl<S: State> State for SetUpdatedAt<S> {
        type PushCount = S::PushCount;
        type UpdatedAt = Set<members::updated_at>;
        type Repository = S::Repository;
        type PullCount = S::PullCount;
        type OwnerDid = S::OwnerDid;
    }
    ///State transition - sets the `repository` field to Set
    pub struct SetRepository<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRepository<S> {}
    impl<S: State> State for SetRepository<S> {
        type PushCount = S::PushCount;
        type UpdatedAt = S::UpdatedAt;
        type Repository = Set<members::repository>;
        type PullCount = S::PullCount;
        type OwnerDid = S::OwnerDid;
    }
    ///State transition - sets the `pull_count` field to Set
    pub struct SetPullCount<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPullCount<S> {}
    impl<S: State> State for SetPullCount<S> {
        type PushCount = S::PushCount;
        type UpdatedAt = S::UpdatedAt;
        type Repository = S::Repository;
        type PullCount = Set<members::pull_count>;
        type OwnerDid = S::OwnerDid;
    }
    ///State transition - sets the `owner_did` field to Set
    pub struct SetOwnerDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetOwnerDid<S> {}
    impl<S: State> State for SetOwnerDid<S> {
        type PushCount = S::PushCount;
        type UpdatedAt = S::UpdatedAt;
        type Repository = S::Repository;
        type PullCount = S::PullCount;
        type OwnerDid = Set<members::owner_did>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `push_count` field
        pub struct push_count(());
        ///Marker type for the `updated_at` field
        pub struct updated_at(());
        ///Marker type for the `repository` field
        pub struct repository(());
        ///Marker type for the `pull_count` field
        pub struct pull_count(());
        ///Marker type for the `owner_did` field
        pub struct owner_did(());
    }
}

/// Builder for constructing an instance of this type
pub struct StatsBuilder<'a, S: stats_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<Datetime>,
        Option<Did<'a>>,
        Option<i64>,
        Option<i64>,
        Option<CowStr<'a>>,
        Option<Datetime>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Stats<'a> {
    /// Create a new builder for this type
    pub fn new() -> StatsBuilder<'a, stats_state::Empty> {
        StatsBuilder::new()
    }
}

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

impl<'a, S: stats_state::State> StatsBuilder<'a, S> {
    /// Set the `lastPull` field (optional)
    pub fn last_pull(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `lastPull` field to an Option value (optional)
    pub fn maybe_last_pull(mut self, value: Option<Datetime>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<'a, S: stats_state::State> StatsBuilder<'a, S> {
    /// Set the `lastPush` field (optional)
    pub fn last_push(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `lastPush` field to an Option value (optional)
    pub fn maybe_last_push(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S> StatsBuilder<'a, S>
where
    S: stats_state::State,
    S::OwnerDid: stats_state::IsUnset,
{
    /// Set the `ownerDid` field (required)
    pub fn owner_did(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> StatsBuilder<'a, stats_state::SetOwnerDid<S>> {
        self._fields.2 = Option::Some(value.into());
        StatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> StatsBuilder<'a, S>
where
    S: stats_state::State,
    S::PullCount: stats_state::IsUnset,
{
    /// Set the `pullCount` field (required)
    pub fn pull_count(
        mut self,
        value: impl Into<i64>,
    ) -> StatsBuilder<'a, stats_state::SetPullCount<S>> {
        self._fields.3 = Option::Some(value.into());
        StatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> StatsBuilder<'a, S>
where
    S: stats_state::State,
    S::PushCount: stats_state::IsUnset,
{
    /// Set the `pushCount` field (required)
    pub fn push_count(
        mut self,
        value: impl Into<i64>,
    ) -> StatsBuilder<'a, stats_state::SetPushCount<S>> {
        self._fields.4 = Option::Some(value.into());
        StatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> StatsBuilder<'a, S>
where
    S: stats_state::State,
    S::Repository: stats_state::IsUnset,
{
    /// Set the `repository` field (required)
    pub fn repository(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> StatsBuilder<'a, stats_state::SetRepository<S>> {
        self._fields.5 = Option::Some(value.into());
        StatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> StatsBuilder<'a, S>
where
    S: stats_state::State,
    S::UpdatedAt: stats_state::IsUnset,
{
    /// Set the `updatedAt` field (required)
    pub fn updated_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> StatsBuilder<'a, stats_state::SetUpdatedAt<S>> {
        self._fields.6 = Option::Some(value.into());
        StatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> StatsBuilder<'a, S>
where
    S: stats_state::State,
    S::PushCount: stats_state::IsSet,
    S::UpdatedAt: stats_state::IsSet,
    S::Repository: stats_state::IsSet,
    S::PullCount: stats_state::IsSet,
    S::OwnerDid: stats_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Stats<'a> {
        Stats {
            last_pull: self._fields.0,
            last_push: self._fields.1,
            owner_did: self._fields.2.unwrap(),
            pull_count: self._fields.3.unwrap(),
            push_count: self._fields.4.unwrap(),
            repository: self._fields.5.unwrap(),
            updated_at: 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>,
        >,
    ) -> Stats<'a> {
        Stats {
            last_pull: self._fields.0,
            last_push: self._fields.1,
            owner_did: self._fields.2.unwrap(),
            pull_count: self._fields.3.unwrap(),
            push_count: self._fields.4.unwrap(),
            repository: self._fields.5.unwrap(),
            updated_at: self._fields.6.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_io_atcr_hold_stats() -> 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("io.atcr.hold.stats"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Repository statistics stored in the hold's embedded PDS. Tracks pull/push counts per owner+repository combination. Record key is deterministic: base32(sha256(ownerDID + \"/\" + repository)[:16]).",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("ownerDid"),
                                SmolStr::new_static("repository"),
                                SmolStr::new_static("pullCount"),
                                SmolStr::new_static("pushCount"),
                                SmolStr::new_static("updatedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("lastPull"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("RFC3339 timestamp of last pull"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("lastPush"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("RFC3339 timestamp of last push"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("ownerDid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "DID of the image owner (e.g., did:plc:xyz123)",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("pullCount"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("pushCount"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("repository"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Repository name (e.g., myapp)"),
                                    ),
                                    max_length: Some(256usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "RFC3339 timestamp of when this record was last updated",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}