{ pkgs, ... }@all: with all;
{
  systemd.timers."nx_cal_lr" = {
    enable = true;
    wantedBy = [ "timers.target" ];
    timerConfig = {
      OnBootSec = "41m";
      OnUnitActiveSec = "24h";
      Unit = "nx_cal_lr.service";
    };
  };

  systemd.services."nx_cal_lr" = {
    script = let 
      nx_cal_lr = (pkgs.writers.writePython3Bin "nx_cal_lr" {
      libraries = with pkgs.python3Packages; [
        ics
        requests
      ];
      flakeIgnore = [ "E302" "E305" "E226" "E501" ];
    } /*python */ ''
from ics import Calendar
import requests

def filter_events(events):
    return [event for event in events if ("LR" in event.name)]
    # return [event for event in events if ("LR" in event.name) or ("TBD" in event.name)]

def fetch_and_save_ical_events(ical_urls, save_path):
    """
    Fetch events from an iCal URL and save them as a single combined calendar.
    """
    try:
        # Create a new combined calendar
        combined_calendar = Calendar()

        for url in ical_urls:
            # Fetch the iCal data
            response = requests.get(url)
            response.raise_for_status()

            # Parse the iCal data
            calendar = Calendar(response.text)

            # Adjust events
            adjusted_events = filter_events(list(calendar.events))

            for event in adjusted_events:
                combined_calendar.events.add(event)

        # Save the combined calendar to a single .ics file
        with open(save_path, 'w') as file:
            file.writelines(combined_calendar.serialize_iter())

        print(f"Saved combined calendar to {save_path}")

    except requests.exceptions.RequestException as e:
        print(f"Error fetching iCal data: {e}")
    except Exception as e:
        print(f"Error processing iCal data: {e}")

if __name__ == "__main__":
    # Replace with your iCal URL and target file path
    ICAL_URLS = [
        "https://zlypher.github.io/lol-events/cal/league-of-legends-nlc.ical",
        "https://zlypher.github.io/lol-events/cal/league-of-legends-emea-masters.ical"
    ]
    SAVE_PATH = "${config.services.nginx.virtualHosts."${hyper.domain}".root}/lr.ics"

    fetch_and_save_ical_events(ICAL_URLS, SAVE_PATH)
'');
    in ''
      ${nx_cal_lr}/bin/nx_cal_lr
    '';
    serviceConfig = {
      Type = "oneshot";
      User = hyper.user;
    };
  };
}
