use anyhow::{Context, Result};
use birdeye_client::client::BirdeyeClient;
use birdeye_client::defi::types::BirdeyeTokenSecurity;

/// Fetch token security data from Birdeye API with automatic percentage normalisation.
///
/// Percentage fields are normalised from Birdeye's decimal fraction format (1.0 = 100%)
/// to the 0–100 scale used by all scoring logic.
///
/// # Examples
///
/// ```no_run
/// use birdeye_client::client::{BirdeyeClient, BirdeyeProvider};
/// use aignt_mint_scoring::fetch_token_security;
///
/// # async fn example() -> anyhow::Result<()> {
/// let client = BirdeyeClient::new("your-api-key", BirdeyeProvider::Uniblock, None)?;
/// let security = fetch_token_security(&client, "So11111111111111111111111111111111111111112").await?;
/// # Ok(())
/// # }
/// ```
pub async fn fetch_token_security(
    client: &BirdeyeClient,
    address: &str,
) -> Result<BirdeyeTokenSecurity> {
    let response = client.get_token_security(address).await?;

    if !response.success {
        anyhow::bail!("Birdeye API returned success=false");
    }

    let mut data = response
        .data
        .context("Birdeye API returned no data for token security")?;

    normalize_percentages(&mut data);

    Ok(data)
}

fn normalize_percentages(data: &mut BirdeyeTokenSecurity) {
    if let Some(v) = data.creator_percentage {
        data.creator_percentage = Some(v * 100.0);
    }
    if let Some(v) = data.owner_percentage {
        data.owner_percentage = Some(v * 100.0);
    }
    if let Some(v) = data.top10_holder_percent {
        data.top10_holder_percent = Some(v * 100.0);
    }
    if let Some(v) = data.top10_user_percent {
        data.top10_user_percent = Some(v * 100.0);
    }
    if let Some(v) = data.metaplex_update_authority_percent {
        data.metaplex_update_authority_percent = Some(v * 100.0);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_normalize_percentages_converts_decimal_to_percent() {
        let mut security = BirdeyeTokenSecurity::default();
        security.top10_holder_percent = Some(1.0);
        security.creator_percentage = Some(0.0);
        security.owner_percentage = Some(0.5);
        security.top10_user_percent = Some(0.95);
        security.metaplex_update_authority_percent = Some(0.0);

        normalize_percentages(&mut security);

        assert!((security.top10_holder_percent.unwrap() - 100.0).abs() < 1e-6);
        assert!((security.creator_percentage.unwrap() - 0.0).abs() < 1e-6);
        assert!((security.owner_percentage.unwrap() - 50.0).abs() < 1e-6);
        assert!((security.top10_user_percent.unwrap() - 95.0).abs() < 1e-6);
        assert!((security.metaplex_update_authority_percent.unwrap() - 0.0).abs() < 1e-6);
    }

    #[test]
    fn test_normalize_percentages_handles_none() {
        let mut security = BirdeyeTokenSecurity::default();
        normalize_percentages(&mut security);
        assert!(security.top10_holder_percent.is_none());
        assert!(security.creator_percentage.is_none());
    }
}
