import json

import numpy as np
import pandas as pd

BASE_MAPPING = {
    "dailyperffee": "total_value_performance_fees",
    "dailyrunningfee": "total_value_management_fees",
    "date": "fee_date",
}


def parse(import_source):
    content = json.load(import_source.file)
    # dailyrunningfees => MANAGEMENT
    # dailyperffee => PERFORMANCE
    # ? => ISSUER
    data = []
    if content:
        overview = content["overview"]
        df = pd.DataFrame(content["fees"]).rename(columns=BASE_MAPPING)
        df["fee_date"] = pd.to_datetime(df["fee_date"], dayfirst=True)
        if not df.empty:
            df = pd.melt(
                df.reset_index(),
                id_vars=["fee_date"],
                value_vars=["total_value_management_fees", "total_value_performance_fees"],
                var_name="type_raw",
                value_name="total_value",
            )
            df["transaction_subtype"] = df["type_raw"].map(
                {"total_value_management_fees": "MANAGEMENT", "total_value_performance_fees": "PERFORMANCE"}
            )
        df = df.drop(columns=df.columns.difference(["fee_date", "transaction_subtype", "total_value"]))
        df["total_value"] = df["total_value"].replace("-", np.nan).astype(float)
        df = df.dropna(subset=["total_value"])
        extra_param = {"product__isin": overview["isin"], "currency__key": overview["currency"]}
        df = df.assign(**extra_param)
        df["fee_date"] = df["fee_date"].dt.strftime("%Y-%m-%d")
        data = df.to_dict("records")
    return {"data": data}
