{ config, lib, pkgs, inputs ? null, ... }:

with lib;

let
  cfg = config.power_manager;
in
{
  options.power_manager = {
    enable = mkEnableOption "power management";

    backend = mkOption {
      type = types.enum [ "auto-cpufreq" "power-profiles-daemon" ];
      default = "auto-cpufreq";
      description = ''
        Power management backend to use.
        - auto-cpufreq: Automatic CPU frequency scaling (better battery life, no manual control)
        - power-profiles-daemon: Manual power profile switching (works with Noctalia shell)
      '';
    };

    settings = mkOption {
      type = types.attrs;
      default = {
        battery = {
          governor = "powersave";
          turbo = "never";
        };
        charger = {
          governor = "performance";
          turbo = "auto";
        };
      };
      description = "Auto-cpufreq configuration settings (only used with auto-cpufreq backend)";
    };

    enableThermald = mkOption {
      type = types.bool;
      default = true;
      description = "Enable thermald for Intel CPU thermal management";
    };

    enableUpower = mkOption {
      type = types.bool;
      default = true;
      description = "Enable UPower for battery monitoring";
    };
  };

  config = mkIf cfg.enable (mkMerge [
    # Common settings for both backends
    {
      services.upower.enable = mkIf cfg.enableUpower true;
      services.thermald.enable = mkIf cfg.enableThermald true;
      powerManagement.enable = true;

      # Disable TLP regardless of backend (conflicts with both)
      services.tlp.enable = mkForce false;
      powerManagement.powertop.enable = mkForce false;
    }

    # auto-cpufreq backend
    (mkIf (cfg.backend == "auto-cpufreq") {
      services.auto-cpufreq = {
        enable = true;
        settings = cfg.settings;
      };

      # Disable power-profiles-daemon (conflicts with auto-cpufreq)
      services.power-profiles-daemon.enable = mkForce false;

      # Don't set a static CPU governor (let auto-cpufreq handle it)
      powerManagement.cpuFreqGovernor = mkForce null;
    })

    # power-profiles-daemon backend
    (mkIf (cfg.backend == "power-profiles-daemon") {
      services.power-profiles-daemon.enable = true;

      # Disable auto-cpufreq (conflicts with power-profiles-daemon)
      services.auto-cpufreq.enable = mkForce false;
    })
  ]);
}
