// @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, 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::{Did, 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};
/// 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]).

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "io.atcr.hold.stats",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Stats<S: BosStr = DefaultStr> {
    ///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)
    pub owner_did: Did<S>,
    ///Number of manifest downloads
    pub pull_count: i64,
    ///Number of manifest uploads
    pub push_count: i64,
    ///Repository name (e.g., myapp)
    pub repository: S,
    ///RFC3339 timestamp of when this record was last updated
    pub updated_at: Datetime,
    #[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 StatsGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Stats<S>,
}

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

/// 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<S: BosStr> = StatsGetRecordOutput<S>;
    type Err = RecordError;
}

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

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

/// Builder for constructing an instance of this type.
pub struct StatsBuilder<St: stats_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<Datetime>,
        Option<Did<S>>,
        Option<i64>,
        Option<i64>,
        Option<S>,
        Option<Datetime>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

impl<St: stats_state::State, S: BosStr> StatsBuilder<St, 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<St: stats_state::State, S: BosStr> StatsBuilder<St, 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<St, S: BosStr> StatsBuilder<St, S>
where
    St: stats_state::State,
    St::OwnerDid: stats_state::IsUnset,
{
    /// Set the `ownerDid` field (required)
    pub fn owner_did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> StatsBuilder<stats_state::SetOwnerDid<St>, S> {
        self._fields.2 = Option::Some(value.into());
        StatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

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

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

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

impl<St, S: BosStr> StatsBuilder<St, S>
where
    St: stats_state::State,
    St::OwnerDid: stats_state::IsSet,
    St::PullCount: stats_state::IsSet,
    St::PushCount: stats_state::IsSet,
    St::Repository: stats_state::IsSet,
    St::UpdatedAt: stats_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Stats<S> {
        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<SmolStr, Data<S>>) -> Stats<S> {
        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()
    }
}