use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

use crate::party_traits::find_fields_in_struct;

pub const TRANSCRIPT_STR: &str = "transcript";

pub fn derive_scribe(input: TokenStream) -> TokenStream {
    // Parsing
    let input = parse_macro_input!(input as DeriveInput);
    let transcript_fields = match find_fields_in_struct(&input, [TRANSCRIPT_STR.to_string()]) {
        Ok(mut results) => results.remove(TRANSCRIPT_STR).unwrap_or_default(),
        Err(e) => return e,
    };

    // Validation
    let ident = match transcript_fields.as_slice() {
        [(ident, _)] =>ident,
        [] => return quote! { compile_error!("Found no field marked with #[transcript] or a field named `transcript`.") }.into(),
        _ => return quote! { compile_error!("Found multiple fields marked with #[transcript] or named `transcript`. Only one is allowed.") }.into(),
    };

    // Implementation
    let struct_name = &input.ident;
    let generics = &input.generics;
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    quote! {
        impl #impl_generics crate::types::party::Scribe for #struct_name #ty_generics #where_clause {
            fn transcript(&mut self) -> &mut impl primitives::transcripts::AutoTranscript {
                &mut self.#ident
            }
        }
    }.into()
}
