import datetime
import os

from dotenv import load_dotenv

load_dotenv()
from pygrister.api import GristApi

PRICE_REGULAR = 3
PRICE_KIDS = 1.5

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


def sync_with_grist(event) -> int:
    """Writes the event's registrations to Grist.
    If a registration already exists for a given household, it is not overwritten.
    Returns the number of new records.
    """
    grist = GristApi(config=config)

    status_code, grist_response = grist.list_records(
        "Transactions", filter={"meal_manager_event_id": [event.id]}
    )

    existing_records = set()
    for entry in grist_response:
        existing_records.add(entry["Partei_Konto"])

    new_records = []

    today = datetime.date.today().isoformat()
    for registration in event.registrations:
        if registration.household.name in existing_records:
            continue
        if registration.num_adult_meals > 0:
            new_records.append(
                {
                    "Datum": event.event_time.date().isoformat(),
                    "Typ": "Essen",
                    "Partei_Konto": registration.household.name,
                    "Betrag": -1 * PRICE_REGULAR * registration.num_adult_meals,
                    "Date_Added": today,
                    "meal_manager_event_id": event.id,
                }
            )
        if registration.num_children_meals > 0:
            new_records.append(
                {
                    "Datum": event.event_time.date().isoformat(),
                    "Typ": "Essen Kind",
                    "Partei_Konto": registration.household.name,
                    "Betrag": -1 * PRICE_KIDS * registration.num_children_meals,
                    "Date_Added": today,
                    "meal_manager_event_id": event.id,
                }
            )
    if new_records:
        grist.add_records("Transactions", new_records)
        return len(new_records)
    else:
        return 0
