from collections import defaultdict
import sys
import openpyxl
from pygrister.api import GristApi
from dotenv import load_dotenv
import os
import datetime
load_dotenv()


config = {
    "GRIST_API_SERVER": "allmende-gufi.de",
    "GRIST_TEAM_SITE": "grist",
    "GRIST_API_KEY": os.getenv("GRIST_API_KEY"),
    "GRIST_DOC_ID": "xmEcaq5pvxUB3mBfEY8BLe"
}

# grist = GristApi(config=config)
#
# result = grist.add_records("Transactions", [{"Datum": "01.01.1900", "Typ": "Essen", "Partei_Konto": "Heinz", "Betrag": 10}])
# print(result)
def read_excel_file(file_path):
    # Load the workbook
    workbook = openpyxl.load_workbook(file_path)

    sheet = workbook["Liste"]

    date = sheet["A1"].value.split()[-1]

    result = {
        "date": date,
        "adult": defaultdict(lambda: 0),
        "children": defaultdict(lambda: 0),
    }
    # Loop through each row in the sheet
    for row in sheet.iter_rows(values_only=True):
        if row[0] == "Essensanmeldung":
            if row[2] == "Erwachsene Portionen":
                result["adult"][row[3]] += row[5]
            if row[2] == "Kinderportionen (ab 7 Jahren)":
                result["children"][row[3]] += row[5]

    # Close the workbook
    workbook.close()

    return result

if __name__ == "__main__":
    filename = sys.argv[1]
    entries = read_excel_file(filename)

    grist = GristApi(config=config)
    records = []

    today = datetime.date.today().isoformat()

    for name, number in entries["adult"].items():
        records.append({
            "Datum": entries["date"],
            "Typ": "Essen",
            "Partei_Konto": name,
            "Betrag": -3.5 * number,
            "Date_Added": today
        })
    for name, number in entries["children"].items():
        records.append({
            "Datum": entries["date"],
            "Typ": "Essen Kind",
            "Partei_Konto": name,
            "Betrag": -2 * number,
            "Date_Added": today
        })

    grist.add_records("Transactions", records)

