import json

import pandas as pd

BASE_MAPPING = {
    "assettype": "underlying_quote__instrument_type",
    "bbgticker": "underlying_quote__ticker",
    "date": "date",
    "fxrates": "currency_fx_rate",
    "numberofshares": "shares",
    "positionccy": "currency__key",
    "positionisin": "underlying_quote__isin",
    "prices": "price",
    "securitysedol": "underlying_quote__sedol",
    "strategyticker": "portfolio__ticker",
    "weightinpercent": "weighting",
}


def parse(import_source):
    content = json.load(import_source.file)
    data = []
    if content:
        df = pd.DataFrame(content["performance"]).rename(columns=BASE_MAPPING)
        df = df.drop(columns=df.columns.difference(BASE_MAPPING.values()))
        if not df.empty:
            df[["shares", "price", "weighting", "currency_fx_rate"]] = df[
                ["shares", "price", "weighting", "currency_fx_rate"]
            ].astype(float)
            df["date"] = pd.to_datetime(df["date"], dayfirst=True).dt.strftime("%Y-%m-%d")
            df["underlying_quote__instrument_type"] = df["underlying_quote__instrument_type"].str.upper()
            df["underlying_quote__currency__key"] = df["currency__key"]
            df["portfolio__instrument_type"] = "INDEX"
            df["portfolio__ticker"] = df["portfolio__ticker"].str.replace(" Index", "")
            data = df.to_dict("records")
    return {"data": data}
