import os
from pathlib import Path
import requests
import frontmatter

def get_API(URL):

    try:
        response = requests.get(URL)
        response.raise_for_status()
        return response.json()

    except requests.exceptoins.RequestException as e:
        raise Exception(f"Failed getting the API response: {e}")


def create_calendar_item(item, filepath):
    print("i will create an item for", item)

    try:
        details = get_API("https://calendar.klank.school/api/event/detail/" + item['slug'])
        print(details)
        post = frontmatter.Post(content=details["description"])

        for key in details:
            post[key] = details[key]


        with open(filepath, 'wb') as f:
            frontmatter.dump(post, f)
            print(f"Created file: {filepath}")

    except Exception as e:
        print(f"An error occurred while getting the calendar events: {str(e)}")
        exit(1)


def get_calendar_events():
    Path("src/content/events").mkdir(parents=True, exist_ok=True)


    # Also get non unrepair events.
    try:
        items = get_API("https://calendar.klank.school/api/events?start=-1")

        for item in items:
            filename = f"{item['slug']}.md"
            filepath = os.path.join("src/content/events", filename)

            if os.path.isfile(filepath):
                print("oh it already exists")
            else:
                print("did not store this yet")
                create_calendar_item(item, filepath)

    except Exception as e:
        print(f"An error occurred while getting the calendar events: {str(e)}")
        exit(1)


def main():
    get_calendar_events()


main()
