// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: sh.tangled.git.temp.listLanguages
//
// 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::string::AtUri;
use jacquard_derive::{IntoStatic, lexicon, 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::git::temp::list_languages;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Language<'a> {
    ///Hex color code for this language
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub color: Option<CowStr<'a>>,
    ///File extensions associated with this language
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub extensions: Option<Vec<CowStr<'a>>>,
    ///Number of files in this language
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_count: Option<i64>,
    ///Programming language name
    #[serde(borrow)]
    pub name: CowStr<'a>,
    ///Percentage of total codebase (0-100)
    pub percentage: i64,
    ///Total size of files in this language (bytes)
    pub size: i64,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ListLanguages<'a> {
    ///Defaults to `"HEAD"`.
    #[serde(default = "_default_ref")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub r#ref: Option<CowStr<'a>>,
    #[serde(borrow)]
    pub repo: AtUri<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ListLanguagesOutput<'a> {
    #[serde(borrow)]
    pub languages: Vec<list_languages::Language<'a>>,
    ///The git reference used
    #[serde(borrow)]
    pub r#ref: CowStr<'a>,
    ///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>,
}


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

#[serde(tag = "error", content = "message")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum ListLanguagesError<'a> {
    /// Repository not found or access denied
    #[serde(rename = "RepoNotFound")]
    RepoNotFound(Option<CowStr<'a>>),
    /// Git reference not found
    #[serde(rename = "RefNotFound")]
    RefNotFound(Option<CowStr<'a>>),
    /// Invalid request parameters
    #[serde(rename = "InvalidRequest")]
    InvalidRequest(Option<CowStr<'a>>),
}

impl core::fmt::Display for ListLanguagesError<'_> {
    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::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

impl<'a> LexiconSchema for Language<'a> {
    fn nsid() -> &'static str {
        "sh.tangled.git.temp.listLanguages"
    }
    fn def_name() -> &'static str {
        "language"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_tangled_git_temp_listLanguages()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

/// Response type for sh.tangled.git.temp.listLanguages
pub struct ListLanguagesResponse;
impl jacquard_common::xrpc::XrpcResp for ListLanguagesResponse {
    const NSID: &'static str = "sh.tangled.git.temp.listLanguages";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = ListLanguagesOutput<'de>;
    type Err<'de> = ListLanguagesError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for ListLanguages<'a> {
    const NSID: &'static str = "sh.tangled.git.temp.listLanguages";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Response = ListLanguagesResponse;
}

/// Endpoint type for sh.tangled.git.temp.listLanguages
pub struct ListLanguagesRequest;
impl jacquard_common::xrpc::XrpcEndpoint for ListLanguagesRequest {
    const PATH: &'static str = "/xrpc/sh.tangled.git.temp.listLanguages";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Request<'de> = ListLanguages<'de>;
    type Response = ListLanguagesResponse;
}

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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetName<S> {}
    impl<S: State> State for SetName<S> {
        type Name = Set<members::name>;
        type Percentage = S::Percentage;
        type Size = S::Size;
    }
    ///State transition - sets the `percentage` field to Set
    pub struct SetPercentage<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPercentage<S> {}
    impl<S: State> State for SetPercentage<S> {
        type Name = S::Name;
        type Percentage = Set<members::percentage>;
        type Size = S::Size;
    }
    ///State transition - sets the `size` field to Set
    pub struct SetSize<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSize<S> {}
    impl<S: State> State for SetSize<S> {
        type Name = S::Name;
        type Percentage = S::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<'a, S: language_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<CowStr<'a>>,
        Option<Vec<CowStr<'a>>>,
        Option<i64>,
        Option<CowStr<'a>>,
        Option<i64>,
        Option<i64>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

impl<'a, S: language_state::State> LanguageBuilder<'a, S> {
    /// Set the `extensions` field (optional)
    pub fn extensions(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> 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<CowStr<'a>>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<'a, S: language_state::State> LanguageBuilder<'a, 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<'a, S> LanguageBuilder<'a, S>
where
    S: language_state::State,
    S::Name: language_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> LanguageBuilder<'a, language_state::SetName<S>> {
        self._fields.3 = Option::Some(value.into());
        LanguageBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

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

impl<'a, S> LanguageBuilder<'a, S>
where
    S: language_state::State,
    S::Name: language_state::IsSet,
    S::Percentage: language_state::IsSet,
    S::Size: language_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Language<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Language<'a> {
        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_git_temp_listLanguages() -> 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.git.temp.listLanguages"),
        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("AT-URI of the repository"),
                                        ),
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                );
                                map
                            },
                            ..Default::default()
                        }),
                    ),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

fn _default_ref() -> Option<CowStr<'static>> {
    Some(CowStr::from("HEAD"))
}

pub mod list_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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRepo<S> {}
    impl<S: State> State for SetRepo<S> {
        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 ListLanguagesBuilder<'a, S: list_languages_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<AtUri<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> ListLanguages<'a> {
    /// Create a new builder for this type
    pub fn new() -> ListLanguagesBuilder<'a, list_languages_state::Empty> {
        ListLanguagesBuilder::new()
    }
}

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

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

impl<'a, S> ListLanguagesBuilder<'a, S>
where
    S: list_languages_state::State,
    S::Repo: list_languages_state::IsUnset,
{
    /// Set the `repo` field (required)
    pub fn repo(
        mut self,
        value: impl Into<AtUri<'a>>,
    ) -> ListLanguagesBuilder<'a, list_languages_state::SetRepo<S>> {
        self._fields.1 = Option::Some(value.into());
        ListLanguagesBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> ListLanguagesBuilder<'a, S>
where
    S: list_languages_state::State,
    S::Repo: list_languages_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> ListLanguages<'a> {
        ListLanguages {
            r#ref: self._fields.0,
            repo: self._fields.1.unwrap(),
        }
    }
}