#!/usr/bin/python3
#
# (C) Copyright 2019
# Christophe Vu-Brugier <cvubrugier@fastmail.fm>
#
# SPDX-License-Identifier: GPL-2.0+
#
# Usage: csv-socgen.py FILE.CSV [DATE]
#

import datetime
import pandas as pd
import sys
from typing import Optional

def csv_filter(filename: str, start_date: Optional[str]) -> None:
    df = pd.read_csv(filename, sep=';', header=1,
                     parse_dates=True, dayfirst=True,
                     usecols=range(4), index_col=0,
                     names=['date', 'description', 'amount', 'currency', ''],
                     decimal=',',
                     encoding='ISO-8859-1')
    if start_date is not None:
        start = datetime.date.fromisoformat(start_date)
        end = datetime.date.today()
        df = df[end:start]
    df['deposit']  = df['amount'].apply(lambda x: x if x > 0 else 0)
    df['withdraw'] = df['amount'].apply(lambda x: abs(x) if x < 0 else 0)
    df.to_csv('gnucash.csv',
              sep=';', decimal=',',
              columns=['description', 'deposit', 'withdraw'])

if __name__ == '__main__':
    filename = sys.argv[1]
    start_date = sys.argv[2] if len(sys.argv) > 2 else None
    csv_filter(filename, start_date)
