{ pkgs, config, lib, ... }:
{
  # ===================
  # Ollama Service
  # ===================
  services.ollama = {
    enable = true;
    acceleration = null;  # CPU only, no GPU
    host = "127.0.0.1";
    port = 11434;
  };

  # ===================
  # PostgreSQL: Letta Database
  # ===================
  services.postgresql = {
    enable = true;
    ensureDatabases = [ "letta" ];
    ensureUsers = [
      {
        name = "letta";
        ensureDBOwnership = true;
      }
    ];

    # Enable TCP connections (required for Docker)
    enableTCPIP = true;

    # Allow letta user to connect via TCP with password
    authentication = lib.mkAfter ''
      # Letta database - TCP password auth for Docker
      host letta letta 127.0.0.1/32 scram-sha-256
      host letta letta ::1/128 scram-sha-256
    '';
    # pgvector is already provided by immich profile via services.immich.database.enableVectorChord
  };

  # ===================
  # Database Setup Service
  # ===================
  # Runs after postgresql to enable pgvector and set password
  systemd.services.raven-db-setup = {
    description = "Setup Letta database with pgvector and password";
    after = [ "postgresql.service" ];
    wantedBy = [ "multi-user.target" ];
    path = [ config.services.postgresql.package ];
    serviceConfig = {
      Type = "oneshot";
      User = "postgres";
      RemainAfterExit = true;
    };
    script = ''
      # Enable pgvector extension
      psql -d letta -c "CREATE EXTENSION IF NOT EXISTS vector;"

      # Set password for letta user
      # TODO: Consider using agenix for production
      psql -c "ALTER USER letta WITH PASSWORD 'letta-dev-password';"
    '';
  };
}
