// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: sh.tangled.repo.languages
//
// 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::value::Data;
use jacquard_derive::{IntoStatic, 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::sh_tangled::repo::languages;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Language<S: BosStr = DefaultStr> {
    ///Hex color code for this language
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<S>,
    ///File extensions associated with this language
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<Vec<S>>,
    ///Number of files in this language
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_count: Option<i64>,
    ///Programming language name
    pub name: S,
    ///Percentage of total codebase (0-100)
    pub percentage: i64,
    ///Total size of files in this language (bytes)
    pub size: i64,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Languages<S: BosStr = DefaultStr> {
    /// Defaults to `"HEAD"`.
    #[serde(default = "_default_ref")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#ref: Option<S>,
    pub repo: S,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct LanguagesOutput<S: BosStr = DefaultStr> {
    pub languages: Vec<languages::Language<S>>,
    ///The git reference used
    pub r#ref: S,
    ///Total number of files analyzed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_files: Option<i64>,
    ///Total size of all analyzed files in bytes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_size: Option<i64>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic
)]

#[serde(tag = "error", content = "message")]
pub enum LanguagesError {
    /// Repository not found or access denied
    #[serde(rename = "RepoNotFound")]
    RepoNotFound(Option<SmolStr>),
    /// Git reference not found
    #[serde(rename = "RefNotFound")]
    RefNotFound(Option<SmolStr>),
    /// Invalid request parameters
    #[serde(rename = "InvalidRequest")]
    InvalidRequest(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for LanguagesError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::RepoNotFound(msg) => {
                write!(f, "RepoNotFound")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::RefNotFound(msg) => {
                write!(f, "RefNotFound")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::InvalidRequest(msg) => {
                write!(f, "InvalidRequest")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Other { error, message } => {
                write!(f, "{}", error)?;
                if let Some(msg) = message {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
        }
    }
}

impl<S: BosStr> LexiconSchema for Language<S> {
    fn nsid() -> &'static str {
        "sh.tangled.repo.languages"
    }
    fn def_name() -> &'static str {
        "language"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_tangled_repo_languages()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

/** Response marker for the `sh.tangled.repo.languages` query.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `LanguagesOutput<S>` for this endpoint.*/
pub struct LanguagesResponse;
impl jacquard_common::xrpc::XrpcResp for LanguagesResponse {
    const NSID: &'static str = "sh.tangled.repo.languages";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = LanguagesOutput<S>;
    type Err = LanguagesError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for Languages<S> {
    const NSID: &'static str = "sh.tangled.repo.languages";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Response = LanguagesResponse;
}

/** Endpoint marker for the `sh.tangled.repo.languages` query.

Path: `/xrpc/sh.tangled.repo.languages`. The request payload type is `Languages<S>`; send that request with `jacquard::Client` or use this marker through lower-level `XrpcEndpoint` APIs.*/
pub struct LanguagesRequest;
impl jacquard_common::xrpc::XrpcEndpoint for LanguagesRequest {
    const PATH: &'static str = "/xrpc/sh.tangled.repo.languages";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Request<S: BosStr> = Languages<S>;
    type Response = LanguagesResponse;
}

pub mod language_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 Name;
        type Percentage;
        type Size;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Name = Unset;
        type Percentage = Unset;
        type Size = Unset;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type Name = Set<members::name>;
        type Percentage = St::Percentage;
        type Size = St::Size;
    }
    ///State transition - sets the `percentage` field to Set
    pub struct SetPercentage<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPercentage<St> {}
    impl<St: State> State for SetPercentage<St> {
        type Name = St::Name;
        type Percentage = Set<members::percentage>;
        type Size = St::Size;
    }
    ///State transition - sets the `size` field to Set
    pub struct SetSize<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSize<St> {}
    impl<St: State> State for SetSize<St> {
        type Name = St::Name;
        type Percentage = St::Percentage;
        type Size = Set<members::size>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `percentage` field
        pub struct percentage(());
        ///Marker type for the `size` field
        pub struct size(());
    }
}

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

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

impl<S: BosStr> Language<S> {
    /// Create a new builder for this type
    pub fn builder() -> LanguageBuilder<language_state::Empty, S> {
        LanguageBuilder::builder()
    }
}

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

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

impl<St: language_state::State, S: BosStr> LanguageBuilder<St, S> {
    /// Set the `color` field (optional)
    pub fn color(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `color` field to an Option value (optional)
    pub fn maybe_color(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: language_state::State, S: BosStr> LanguageBuilder<St, S> {
    /// Set the `extensions` field (optional)
    pub fn extensions(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `extensions` field to an Option value (optional)
    pub fn maybe_extensions(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St: language_state::State, S: BosStr> LanguageBuilder<St, S> {
    /// Set the `fileCount` field (optional)
    pub fn file_count(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `fileCount` field to an Option value (optional)
    pub fn maybe_file_count(mut self, value: Option<i64>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> LanguageBuilder<St, S>
where
    St: language_state::State,
    St::Name: language_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<S>,
    ) -> LanguageBuilder<language_state::SetName<St>, S> {
        self._fields.3 = Option::Some(value.into());
        LanguageBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LanguageBuilder<St, S>
where
    St: language_state::State,
    St::Percentage: language_state::IsUnset,
{
    /// Set the `percentage` field (required)
    pub fn percentage(
        mut self,
        value: impl Into<i64>,
    ) -> LanguageBuilder<language_state::SetPercentage<St>, S> {
        self._fields.4 = Option::Some(value.into());
        LanguageBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LanguageBuilder<St, S>
where
    St: language_state::State,
    St::Size: language_state::IsUnset,
{
    /// Set the `size` field (required)
    pub fn size(
        mut self,
        value: impl Into<i64>,
    ) -> LanguageBuilder<language_state::SetSize<St>, S> {
        self._fields.5 = Option::Some(value.into());
        LanguageBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LanguageBuilder<St, S>
where
    St: language_state::State,
    St::Name: language_state::IsSet,
    St::Percentage: language_state::IsSet,
    St::Size: language_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Language<S> {
        Language {
            color: self._fields.0,
            extensions: self._fields.1,
            file_count: self._fields.2,
            name: self._fields.3.unwrap(),
            percentage: self._fields.4.unwrap(),
            size: self._fields.5.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>>) -> Language<S> {
        Language {
            color: self._fields.0,
            extensions: self._fields.1,
            file_count: self._fields.2,
            name: self._fields.3.unwrap(),
            percentage: self._fields.4.unwrap(),
            size: self._fields.5.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_sh_tangled_repo_languages() -> 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("sh.tangled.repo.languages"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("language"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("name"), SmolStr::new_static("size"),
                            SmolStr::new_static("percentage")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("color"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Hex color code for this language"),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("extensions"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "File extensions associated with this language",
                                    ),
                                ),
                                items: LexArrayItem::String(LexString {
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("fileCount"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Programming language name"),
                                ),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("percentage"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("size"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcQuery(LexXrpcQuery {
                    parameters: Some(
                        LexXrpcQueryParameter::Params(LexXrpcParameters {
                            required: Some(vec![SmolStr::new_static("repo")]),
                            properties: {
                                #[allow(unused_mut)]
                                let mut map = BTreeMap::new();
                                map.insert(
                                    SmolStr::new_static("ref"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "Git reference (branch, tag, or commit SHA)",
                                            ),
                                        ),
                                        ..Default::default()
                                    }),
                                );
                                map.insert(
                                    SmolStr::new_static("repo"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "Repository identifier in format 'did:plc:.../repoName'",
                                            ),
                                        ),
                                        ..Default::default()
                                    }),
                                );
                                map
                            },
                            ..Default::default()
                        }),
                    ),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

fn _default_ref<S: jacquard_common::FromStaticStr>() -> Option<S> {
    Some(S::from_static("HEAD"))
}

pub mod languages_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 Repo;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Repo = Unset;
    }
    ///State transition - sets the `repo` field to Set
    pub struct SetRepo<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRepo<St> {}
    impl<St: State> State for SetRepo<St> {
        type Repo = Set<members::repo>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `repo` field
        pub struct repo(());
    }
}

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

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

impl<S: BosStr> Languages<S> {
    /// Create a new builder for this type
    pub fn builder() -> LanguagesBuilder<languages_state::Empty, S> {
        LanguagesBuilder::builder()
    }
}

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

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

impl<St: languages_state::State, S: BosStr> LanguagesBuilder<St, S> {
    /// Set the `ref` field (optional)
    pub fn r#ref(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `ref` field to an Option value (optional)
    pub fn maybe_ref(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> LanguagesBuilder<St, S>
where
    St: languages_state::State,
    St::Repo: languages_state::IsUnset,
{
    /// Set the `repo` field (required)
    pub fn repo(
        mut self,
        value: impl Into<S>,
    ) -> LanguagesBuilder<languages_state::SetRepo<St>, S> {
        self._fields.1 = Option::Some(value.into());
        LanguagesBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> LanguagesBuilder<St, S>
where
    St: languages_state::State,
    St::Repo: languages_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Languages<S> {
        Languages {
            r#ref: self._fields.0,
            repo: self._fields.1.unwrap(),
        }
    }
}