use crate::utils::qdf::core::*;
use polars::prelude::*;
use std::error::Error;

const QDF_INDEX_COLUMNS: [&str; 3] = ["real_date", "cid", "xcat"];

/// Update a Quantamental DataFrame with new data.
/// # Arguments:
/// - `df`: The original DataFrame
/// - `df_add`: The new DataFrame to add
/// - `xcat_replace`: !NOT IMPLEMENTED! If true, replace existing xcats with new ones.
///
pub fn update_dataframe(
    df: &DataFrame,
    df_add: &DataFrame,
    xcat_replace: bool,
) -> Result<DataFrame, Box<dyn Error>> {
    check_quantamental_dataframe(df)?;
    check_quantamental_dataframe(df_add)?;
    if df.is_empty() {
        return Ok(df_add.clone());
    } else if df_add.is_empty() {
        return Ok(df.clone());
    };
    println!(
        "xcat_replace not implemented yet (passed value: {})",
        xcat_replace
    );
    // vstack and drop duplicates keeping last
    let mut new_df = df.vstack(df_add)?;
    // help?
    let idx_cols_vec = QDF_INDEX_COLUMNS
        .iter()
        .map(|s| s.to_string())
        .collect::<Vec<String>>();

    new_df = new_df.unique_stable(Some(&idx_cols_vec), UniqueKeepStrategy::Last, None)?;

    Ok(new_df)
}
