{
  config,
  lib,
  pkgs,
  namespace,
  inputs,
  ...
}:
with lib;
let
  cfg = config.${namespace}.services.home-assistant;
in
{
  disabledModules = [
    "services/home-automation/home-assistant.nix"
  ];

  imports = [
    "${inputs.nixpkgs-unstable}/nixos/modules/services/home-automation/home-assistant.nix"
  ];

  config = mkIf cfg.enable {

    services.home-assistant = {
      enable = true;
      package = pkgs.unstable.home-assistant;
      openFirewall = true;
      configDir = "/var/lib/homeassistant";
      configWritable = true; # todo
      # All components
      # extraComponents = config.services.home-assistant.package.availableComponents;
      extraComponents = [
        "accuweather"
        "adguard"
        "air_quality"
        "apcupsd"
        "apple_tv"
        "analytics"
        "backup"
        "bluetooth"
        "bluetooth_adapters"
        "bluetooth_le_tracker"
        "brother"
        "browser"
        "button"
        "caldav"
        "calendar"
        "camera"
        "cast"
        "climate"
        "cloud"
        "cloudflare"
        "co2signal"
        "coinbase"
        "color_extractor"
        "config"
        "configurator"
        "counter"
        "cpuspeed"
        "date"
        "datetime"
        "deluge"
        "device_automation"
        "device_sun_light_trigger"
        "device_tracker"
        "dhcp"
        "diagnostics"
        "discord"
        "dlna_dmr"
        "dlna_dms"
        "downloader"
        "ecobee"
        "energy"
        "epic_games_store"
        "esphome"
        "event"
        "fan"
        "fastdotcom"
        "ffmpeg"
        "ffmpeg_motion"
        "ffmpeg_noise"
        "file"
        "file_upload"
        "filesize"
        "filter"
        "folder"
        "fully_kiosk"
        "generic"
        "generic_thermostat"
        # "geo_json_events"
        # "geo_location"
        # "geo_rss_events"
        "github"
        "gitlab_ci"
        "glances"
        "google"
        "google_cloud"
        "google_drive"
        "google_mail"
        "google_maps"
        "google_photos"
        "google_translate"
        "govee_ble"
        "gpsd"
        "gpslogger"
        "hardware"
        "hddtemp"
        "hdmi_cec"
        "history"
        "history_stats"
        "holiday"
        "homeassistant"
        "homeassistant_alerts"
        "homeassistant_sky_connect"
        "homekit"
        "homekit_controller"
        "http"
        "humidifier"
        "ibeacon"
        "image"
        "image_processing"
        "image_upload"
        "immich"
        "input_boolean"
        "input_button"
        "input_datetime"
        "input_number"
        "input_select"
        "input_text"
        "ios"
        "ipp"
        "isal"
        "jellyfin"
        "lidarr"
        "light"
        "litterrobot"
        "local_calendar"
        "local_file"
        "local_ip"
        "local_todo"
        "logbook"
        "logentries"
        "logger"
        "lovelace"
        "manual_mqtt"
        "matter"
        "met"
        "microsoft"
        "min_max"
        "mobile_app"
        "mqtt"
        "music_assistant"
        "ntfy"
        "nut"
        "nextcloud"
        "notify"
        "nws"
        "ollama"
        "onedrive"
        "onkyo"
        "openhardwaremonitor"
        "opensky"
        "openweathermap"
        "open_router"
        "paperless_ngx"
        "persistent_notification"
        "pinecil"
        "ping"
        "piper"
        "playstation_network"
        "radarr"
        "radio_browser"
        "raspberry_pi"
        "recorder"
        "reddit"
        "remote"
        "remote_calendar"
        "remote_rpi_gpio"
        "roborock" # currently broken
        "samsungtv"
        "schedule"
        "script"
        "search"
        "season"
        "select"
        "sense"
        "sensor"
        "shopping_list"
        "simplefin"
        "smartthings"
        "sonarr"
        "speedtestdotnet"
        "sql"
        "ssdp"
        "statistics"
        "stream"
        "subaru"
        "sun"
        "switch"
        "system_health"
        "system_log"
        "systemmonitor"
        "tailscale"
        "tasmota"
        "tcp"
        "template"
        "text"
        "thread"
        "time"
        "time_date"
        "timer"
        "torque"
        "tplink"
        "tuya"
        "upnp"
        "uptime"
        "usb"
        "vacuum"
        "vlc"
        "vesync"
        "wake_on_lan"
        "waze_travel_time"
        "weather"
        "weatherkit"
        "webdav"
        "webhook"
        "whisper"
        "whois"
        "workday"
        "wyoming"
        "youtube"
        "zeroconf"
        "zha"
        "zone"
      ];

      customComponents =
        with pkgs.home-assistant-custom-components;
        [
          # nixpkgs
          auth_oidc
          better_thermostat
          localtuya
          luxer_one
          prometheus_sensor
          roborock_custom_map
          smartir
          versatile_thermostat
        ]
        ++ (with pkgs.${namespace}; [
          ha-anycubic
          ha-bambulab
          ha-bedjet
          ha-gehome
          ha-icloud3
          ha-local-llm
          ha-mail-and-packages
          ha-nanokvm
          ha-openhasp
          ha-overseerr
          ha-petlibro
          ha-wyzeapi
        ]);

      customLovelaceModules = with pkgs.home-assistant-custom-lovelace-modules; [
        atomic-calendar-revive
        bubble-card
        button-card
        hourly-weather
        mini-graph-card
        mini-media-player
        multiple-entity-row
        mushroom
        vacuum-card
        weather-chart-card
        zigbee2mqtt-networkmap
      ];
      # use postgresql instead of sqlite
      extraPackages =
        ps: with ps; [
          pkgs.${namespace}.python-roborock
          # pkgs.${namespace}.pyvesync
          #     # Core functionality
          #     aiohttp
          #     aiodns
          #     paho-mqtt
          #     pillow
          #     pytz
          #     pyyaml
          #     sqlalchemy

          #     # Discovery & networking
          #     zeroconf
          #     netdisco
          #     ifaddr
          #     ssdp

          #     # Device protocols
          #     pyserial # Serial communications
          #     bluepy # Bluetooth LE

          #     # Smart home ecosystems
          #     mutagen # Media file metadata
          #     pysonos # Sonos
          #     pywemo # Belkin WeMo
          #     python-miio # Xiaomi devices
          #     python-kasa # TP-Link

          #     # Sensors & monitoring
          #     meteocalc # Weather calculations
          #     speedtest-cli # Internet speed

          #     # Visualization & UI
          #     matplotlib # Graphing

          #     # Security
          #     bcrypt
          #     cryptography
          #     pyjwt

          #     # Media
          #     ha-ffmpeg # Camera streams

          #     # Specialized integrations
          #     python-matter-server # Matter protocol

          #     # System integrations
          #     psutil # System monitoring

          psycopg2
          #     numpy
          #     hassil
          #     pyturbojpeg
          #     paho-mqtt
          #     pychromecast
          #     pyatv
          #     python-otbr-api
          #     brother
          #     pyipp
          #     govee-ble
          #     adguardhome
          #     nextcord
          #     aiogithubapi
          #     jellyfin-apiclient-python
          #     pylitterbot
          #     dateparser
          #     aionut
          #     nextcloudmonitor
          #     ollama
          #     pynecil
          #     aiopyarr
          #     pysabnzbd
          #     getmac
          #     zigpy
          #     bellows # For Zigbee EmberZNet-based adapters
          #     zigpy-xbee # For XBee adapters
          #     zigpy-deconz # For ConBee/RaspBee adapters
          #     pyicloud # iCloud
          #     pyatv # Apple TV
          #     opencv-python
          #     face-recognition
          #     ibeacon-ble
          #     gehomesdk
          #     onedrive-personal-sdk
          #     pkgs.${namespace}.python-steam
          #     apple-weatherkit

          #     samsungctl
          #     samsungtvws

          #     aiohomekit

          #     icmplib
          #     aioelectricitymaps
          #     wyoming
          #     pysmartthings
          #     wakeonlan
          #     ephem
        ];

      config = {
        # Includes dependencies for a basic setup
        # https://www.home-assistant.io/integrations/default_config/
        default_config = { };

        cloud = false;

        frontend = {
          themes = "!include_dir_merge_named themes";
        };

        "automation manual" = "!include_dir_merge_list /etc/hass";
        "automation ui" = "!include automations.yaml";
        "scene ui" = "!include scenes.yaml";
        "script ui" = "!include scripts.yaml";

        http = {
          use_x_forwarded_for = true;
          trusted_proxies = [
            "172.30.33.0/24"
            "10.0.1.4"
            "10.0.1.3"
            "10.0.1.18"
            "10.0.1.0/24"
          ];
        };

        recorder = {
          # db_url = "postgresql://@/hass"; # local DB
          db_url = "postgresql://homeassistant@10.0.1.3/homeassistant";
          purge_keep_days = 180;
        };

        auth_header = {
          debug = false;
          username_header = "X-authentik-username";
        };

        # https://www.home-assistant.io/integrations/ota_updater/
        zha.zigpy_config.ota.z2m_remote_index = "https://raw.githubusercontent.com/Koenkk/zigbee-OTA/master/index.json";

        openhasp = {
          plate = {
            objects = [
              {
                obj = "p0b1"; # temperature label on all pages
                properties = {
                  "text" = ''{{ states("sensor.thermostat_current_temperature") }}°F'';
                };
              }
              {
                obj = "p1b2"; # light-switch toggle button
                properties = {
                  "val" = ''{{ 1 if states("light.living_room_lights") == "on" else 0 }}'';
                  "text" = ''{{ "\uE6E8" if is_state("light.living_room_lights", "on") else "\uE335" | e }}'';
                };
                event = {
                  "up" = {
                    service = "homeassistant.toggle";
                    entity_id = "light.living_room_lights";
                  };
                };
              }
              {
                obj = "p1b3"; # dropdown
                event = {
                  "changed" = {
                    service = "persistent_notification.create";
                    data = {
                      message = "I like {{ text }}";
                    };
                  };
                };
              }
            ];
          };
        };
      };
    };
  };
}
