from datetime import datetime, date
import recurring_ical_events
import requests
from icalendar import Calendar
import locale
import sys

def fetch_upcoming_events(ics_url):
    # Set German locale
    locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
    
    response = requests.get(ics_url)
    calendar = Calendar.from_ical(response.content)
    
    # Get recurring and non-recurring events
    events = recurring_ical_events.of(calendar).after(datetime.now())
    
    for event in events:
        start = event.get('dtstart').dt
        out_summary = event.get('summary')
        location = event.get('location', 'No location specified')
        
        out_startdate = start.strftime("%a. %-d. %B %Y")

        # Format output based on whether it's an all-day event
        if isinstance(start, date) and not isinstance(start, datetime):
            out_starttime = "&nbsp;"
        else:
            out_starttime = start.strftime('%-H:%M')
            
        if location != 'No location specified':
            out_location = location
        else:
            out_location = "&nbsp;"

        print(f"* <div>{out_summary}</div>&nbsp;")
        print(f"  * <div>{out_startdate}</div>&nbsp;")
        print(f"  * <div>{out_starttime}</div>&nbsp;")
        print(f"  * <div>{out_location}</div>&nbsp;")


if __name__ == "__main__":

    ics_url = sys.argv[1]

    # ics_url = "https://backoffice.pc-stammertal.ch/remote.php/dav/public-calendars/RqLX5wj25aY6cpnP?export"

    print("_model: page")
    print("---")
    print("title: Termine")
    print("---")
    print("body:")
    print("")
    fetch_upcoming_events(ics_url)
    print("")
    print("---")
    print("_template: page.html")
    print("")
    print("")