use std::fs;

use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

use crate::array_to_tokenstream;

/// Generates the `TokenStream` for the `Sound` enum and its binary-search `from_name`/`to_name` methods.
pub fn build() -> TokenStream {
    let sound: Vec<String> =
        serde_json::from_str(&fs::read_to_string("../../assets/sounds.json").unwrap())
            .expect("Failed to parse sounds.json");

    let variants = array_to_tokenstream(&sound);

    let mut sorted_sound = sound.clone();
    sorted_sound.sort();

    let lookup_table = sorted_sound.iter().map(|s| {
        let variant_name = format_ident!("{}", s.to_pascal_case());
        quote! { (#s, Self::#variant_name) }
    });

    let variants_list = sound.iter().map(|s| {
        let variant_name = format_ident!("{}", s.to_pascal_case());
        quote! { Self::#variant_name, }
    });

    let names_list = sound.iter().map(|s| quote! { #s });

    quote! {
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        #[repr(u16)]
        pub enum Sound {
            #variants
        }

        impl Sound {
            pub const NAMES: &[&str] = &[ #(#names_list),* ];

            #[allow(clippy::large_stack_arrays)]
            const LOOKUP: &[(&str, Self)] = &[
                    #(#lookup_table),*
            ];

            #[must_use]
            pub fn from_name(name: &str) -> Option<Self> {
                Self::LOOKUP
                    .binary_search_by_key(&name, |&(k, _)| k)
                    .ok()
                    .map(|idx| Self::LOOKUP[idx].1)
            }

            #[must_use]
            pub const fn to_name(&self) -> &'static str {
                Self::NAMES[*self as usize]
            }

            #[must_use]
            #[allow(clippy::large_stack_arrays, clippy::too_many_lines)]
            pub const fn slice() -> &'static [Self] {
                &[#(#variants_list)*]
            }
        }
    }
}
