import pandas as pd

from riskipy.riskiconn import S3Handler
from riskipy.riskiconn.file_system.file_types import SupportedFileTypes

from src.config import data_s3_path, data_file_name, cat_features, cont_features

pd.set_option("precision", 3)
pd.set_option("max_colwidth", 20)


def get_samples():
    s3 = S3Handler()
    df = s3.read_df_typed(f"{data_s3_path}/{data_file_name}", SupportedFileTypes.CSV, verbose=True)
    df["chargeback_date"] = pd.to_datetime(df["chargeback_date"])
    df = df.set_index("order_id")
    print(
        pd.crosstab(
            df["formatted_credit_card_company"],
            df["dispute_status"],
            margins=True,
            normalize="index"
        )
    )
    return df

def create_row_comparrison(df, feature):
    most_frequent_cat = df[feature].value_counts(normalize=True).index[0]
    feature_freq = df.groupby("formatted_credit_card_company")[feature].value_counts()
    feature_freq_norm = df.groupby("formatted_credit_card_company")[feature].value_counts(normalize=True)
    # create freq dict
    feature_dict = {
        "most_frequent_category": most_frequent_cat,
        # "MasterCard_freq": feature_freq["MasterCard"][most_frequent_cat],
        # "Visa_freq": feature_freq["Visa"][most_frequent_cat],
        "MasterCard": feature_freq_norm["MasterCard"][most_frequent_cat],
        "Visa": feature_freq_norm["Visa"][most_frequent_cat]
    }
    return feature_dict

def display_cross_tab(df):
    categorical_one_way = {}
    feature_dict = create_row_comparrison(df, "dispute_status")
    categorical_one_way.update({"dispute_status": feature_dict})

    for feature in cat_features:
        if feature not in ["formatted_credit_card_company"]:
            feature_dict = create_row_comparrison(df, feature)
            categorical_one_way.update({feature: feature_dict})

    categorical_describe = pd.DataFrame(categorical_one_way).T
    card_company_grouper = df.groupby("formatted_credit_card_company")[cont_features]
    cont_mean = card_company_grouper.mean().round(5).T
    cont_freq = card_company_grouper.count().round(5).T.add_suffix("_freq")

    features_crostab = categorical_describe.append(pd.concat([cont_mean], axis=1))
    features_crostab["abs_diff_pct"] = abs(1 - features_crostab["MasterCard"] / features_crostab["Visa"])
    features_crostab.sort_values("abs_diff_pct", ascending=False, inplace=True)
    # print(features_crostab)
    return features_crostab


