{ config
, lib
, pkgs
, ...
}:

with lib;
let
  cfg = config.my.programs.ledger;
in
{
  options.my.programs.ledger.enable = mkEnableOption "ledger";

  config = mkIf cfg.enable {
    my.shell = {
      variables = {
        LEDGER_FILE = "/home/moritz/Nextcloud/Notes/ledger/main.ledger";
      };
      aliases =
        let
          applyCommon = _: command: "${command} --payee note --strict --explicit";
        in
        mapAttrs applyCommon {
          bal = "ledger bal";
          balcash = "ledger bal -R -X € --current --flat ^assets:bank ^liabilities";
          balnet = "ledger bal -R -X € --current --depth 2 ^assets ^liabilities";
          bud = ''ledger bal --budget --unbudgeted -p "this month"'';
          budr = ''ledger reg --budget --unbudgeted -p "this month"'';
          reg = "ledger reg -R -V --tail 15";
        };
    };
    environment.systemPackages = with pkgs; let
      reg-copy = writeShellApplication {
        name = "reg-copy";

        runtimeInputs = [ ledger xclip ];

        text = ''
          table="$(printf '%-10s %-30s %8s %8s\n' Datum Beschreibung Einzeln Gesamt && ledger reg -V --format '%10D %.30P %8t %8T\n' "$@")"
          echo "$table"
          echo "$table" | xclip -selection clipboard
        '';
      };
    in
    [ ledger reg-copy hledger hledger-ui hledger-web ];
    home-manager.users.moritz = {
      xdg.configFile = {
        "fish/completions/ledger.fish" = {
          text = builtins.readFile ./ledger.fish;
        };
      };
    };
  };
}
