//! Personalization context building for the RETRIEVE executor.
//!
//! Constructs a `UserContext` from the interaction ledger and creator-items
//! bitmap. The resulting per-item boost map is normalized to `[0.0, 1.0]`.

use std::collections::HashMap;

use crate::entities::{CreatorItemsBitmap, InteractionLedger};
use crate::ranking::executor::UserContext;
use crate::schema::Timestamp;

/// Build a `UserContext` for personalized scoring.
///
/// Fetches the user's top interacted creators from the `InteractionLedger`,
/// then expands each creator into their item set via `CreatorItemsBitmap`.
/// The resulting per-item boost map is normalized to `[0.0, 1.0]`.
pub(crate) fn build_user_context(
    user_id: u64,
    now: Timestamp,
    interaction_ledger: Option<&InteractionLedger>,
    creator_items: Option<&CreatorItemsBitmap>,
) -> UserContext {
    let now_ns = now.as_nanos();

    // Get top creators from the interaction ledger.
    let top_creators = interaction_ledger
        .map(|il| il.top_creators(user_id, 50, now_ns))
        .unwrap_or_default();

    // Build per-item boost map from creator items.
    let mut creator_interaction_boosts: HashMap<u32, f64> = HashMap::new();
    if let Some(creator_items) = creator_items {
        for (creator_id, weight) in &top_creators {
            if let Some(bitmap) = creator_items.get(*creator_id) {
                for item_id in &bitmap {
                    creator_interaction_boosts.insert(item_id, *weight);
                }
            }
        }
    }

    // Normalize boost values to [0.0, 1.0] so the highest-interacted
    // creator gets boost=1.0 and the interaction boost weight constant
    // controls the absolute magnitude.
    if !creator_interaction_boosts.is_empty() {
        let max_weight = creator_interaction_boosts
            .values()
            .copied()
            .fold(0.0_f64, f64::max);
        if max_weight > f64::EPSILON {
            for val in creator_interaction_boosts.values_mut() {
                *val /= max_weight;
            }
        }
    }

    UserContext {
        user_id,
        creator_interaction_boosts,
    }
}
