import json

import pandas as pd

BASE_MAPPING = {
    "counterpartyname": "bank",
    "index": "underlying_instrument__ticker",
    "isin": "underlying_instrument__isin",
    "price": "price",
    "quantity": "shares",
    "tradedate": "transaction_date",
    "side": "transaction_subtype",
}


def parse(import_source):
    content = json.load(import_source.file)
    data = []
    if content:
        df = pd.DataFrame(content["trade"]).rename(columns=BASE_MAPPING)
        df = df.drop(columns=df.columns.difference(BASE_MAPPING.values()))
        if not df.empty:
            df[["shares", "price"]] = df[["shares", "price"]].astype(float)
            df.loc[df["transaction_subtype"] == "S", "transaction_subtype"] = "REDEMPTION"
            df.loc[df["transaction_subtype"] == "B", "transaction_subtype"] = "SUBSCRIPTION"

            sell_idx = df["transaction_subtype"] == "REDEMPTION"
            df.loc[sell_idx, "shares"] = -df.loc[sell_idx, "shares"].abs()

            df["shares"] = -1 * df["shares"]
            df["transaction_date"] = pd.to_datetime(df["transaction_date"], dayfirst=True).dt.strftime("%Y-%m-%d")
            df.loc[df["shares"] < 0, "transaction_subtype"] = "REDEMPTION"
            df.loc[df["shares"] >= 0, "transaction_subtype"] = "SUBSCRIPTION"
            df["portfolio__isin"] = df["underlying_instrument__isin"]
            df["underlying_instrument__instrument_type"] = "product"
            df["portfolio__instrument_type"] = df["underlying_instrument__instrument_type"]

            data = df.to_dict("records")
    return {"data": data}
