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

with lib;

let
  cfg = config.home.roles.email;
  isLinux = pkgs.stdenv.isLinux;
in
{
  options.home.roles.email = {
    enable = mkEnableOption "Enable email with mu4e, mbsync, and msmtp";
  };

  config = mkIf cfg.enable {
    home.packages = with pkgs; [
      isync      # provides mbsync for IMAP sync
      msmtp      # for SMTP sending
      mu         # email indexer for mu4e
      mu.mu4e    # mu4e elisp files for Emacs
      openssl    # for certificate management
    ];

    # Ensure Mail directory exists
    home.file."Mail/.keep".text = "";

    # mbsync configuration
    home.file.".mbsyncrc".text = ''
      # IMAP Account Configuration
      IMAPAccount proton
      Host proton.johnogle.info
      Port 143
      User john@ogle.fyi
      PassCmd "${pkgs.rbw}/bin/rbw get proton.johnogle.info"
      TLSType STARTTLS
      AuthMechs PLAIN

      # Remote Storage
      IMAPStore proton-remote
      Account proton

      # Local Storage
      MaildirStore proton-local
      Path ~/Mail/
      Inbox ~/Mail/INBOX
      SubFolders Verbatim

      # Channel Configuration - Main (excludes Sent)
      Channel proton-main
      Far :proton-remote:
      Near :proton-local:
      Patterns * !Sent
      Create Both
      Expunge Both
      SyncState *

      # Channel Configuration - Sent (pull only)
      Channel proton-sent
      Far :proton-remote:Sent
      Near :proton-local:Sent
      Create Near
      Expunge Near
      Sync Pull
      SyncState *

      # Group both channels
      Group proton
      Channel proton-main
      Channel proton-sent
    '';

    # msmtp configuration
    home.file.".msmtprc".text = ''
      # Default settings
      defaults
      auth           plain
      tls            on
      tls_starttls   on
      tls_trust_file /etc/ssl/certs/ca-certificates.crt
      logfile        ${config.home.homeDirectory}/.msmtp.log

      # Proton mail account
      account        proton
      host           proton.johnogle.info
      port           25
      from           john@ogle.fyi
      user           john@ogle.fyi
      passwordeval   rbw get proton.johnogle.info

      # Set default account
      account default : proton
    '';

    # Linux-only: Systemd service for mail sync (Darwin uses launchd instead)
    systemd.user.services = mkIf isLinux {
      mbsync = {
        Unit = {
          Description = "Mailbox synchronization service";
          After = [ "network-online.target" ];
          Wants = [ "network-online.target" ];
        };
        Service = {
          Type = "oneshot";
          ExecStart = "${pkgs.bash}/bin/bash -c 'mkdir -p ~/Mail && ${pkgs.isync}/bin/mbsync -a && (${pkgs.mu}/bin/mu info >/dev/null 2>&1 || ${pkgs.mu}/bin/mu init --maildir ~/Mail --personal-address=john@ogle.fyi) && ${pkgs.mu}/bin/mu index'";
          Environment = "PATH=${pkgs.rbw}/bin:${pkgs.coreutils}/bin";
          StandardOutput = "journal";
          StandardError = "journal";
        };
      };
    };

    # Linux-only: Systemd timer for automatic sync
    systemd.user.timers = mkIf isLinux {
      mbsync = {
        Unit = {
          Description = "Mailbox synchronization timer";
        };
        Timer = {
          OnBootSec = "2min";
          OnUnitActiveSec = "5min";
          Unit = "mbsync.service";
        };
        Install = {
          WantedBy = [ "timers.target" ];
        };
      };
    };
  };
}
