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

let
  cfg = config.services.prismnet;
  tomlFormat = pkgs.formats.toml { };
  generatedConfig = {
    grpc_addr = "0.0.0.0:${toString cfg.port}";
    http_addr = "0.0.0.0:${toString cfg.httpPort}";
    log_level = "info";
    metadata_backend = cfg.metadataBackend;
    single_node = cfg.singleNode;
    auth = {
      iam_server_addr =
        if cfg.iamAddr != null
        then cfg.iamAddr
        else "127.0.0.1:50080";
    };
  }
  // lib.optionalAttrs (cfg.chainfireAddr != null) {
    chainfire_endpoint = "http://${cfg.chainfireAddr}";
  }
  // lib.optionalAttrs (cfg.flaredbAddr != null) {
    flaredb_endpoint = cfg.flaredbAddr;
  }
  // lib.optionalAttrs (cfg.databaseUrl != null) {
    metadata_database_url = cfg.databaseUrl;
  };
  prismnetConfigFile = tomlFormat.generate "prismnet.toml" (lib.recursiveUpdate generatedConfig cfg.settings);
in
{
  options.services.prismnet = {
    enable = lib.mkEnableOption "prismnet service";

    port = lib.mkOption {
      type = lib.types.port;
      default = 50081;
      description = "Port for prismnet gRPC API";
    };

    httpPort = lib.mkOption {
      type = lib.types.port;
      default = 8087;
      description = "Port for prismnet HTTP REST API";
    };

    iamAddr = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = "IAM service endpoint address (host:port)";
      example = "10.0.0.1:50080";
    };

    chainfireAddr = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = "ChainFire endpoint address (host:port) for cluster coordination only";
      example = "10.0.0.1:2379";
    };

    flaredbAddr = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = "FlareDB endpoint address (host:port) for metadata/user data";
      example = "10.0.0.1:2479";
    };

    metadataBackend = lib.mkOption {
      type = lib.types.enum [ "flaredb" "postgres" "sqlite" ];
      default = "flaredb";
      description = "Metadata backend for PrismNET.";
    };

    databaseUrl = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = "SQL database URL for metadata (required when metadataBackend is postgres/sqlite).";
      example = "postgres://prismnet:secret@10.0.0.10:5432/prismnet";
    };

    singleNode = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "Enable single-node mode (required when metadata backend is SQLite)";
    };

    dataDir = lib.mkOption {
      type = lib.types.path;
      default = "/var/lib/prismnet";
      description = "Data directory for prismnet";
    };

    settings = lib.mkOption {
      type = lib.types.attrs;
      default = {};
      description = "Additional configuration settings";
    };

    package = lib.mkOption {
      type = lib.types.package;
      default = pkgs.prismnet-server or (throw "prismnet-server package not found");
      description = "Package to use for prismnet";
    };
  };

  config = lib.mkIf cfg.enable {
    # Create system user
    users.users.prismnet = {
      isSystemUser = true;
      group = "prismnet";
      description = "PrismNet service user";
      home = cfg.dataDir;
    };

    users.groups.prismnet = {};

    # Create systemd service
    systemd.services.prismnet = {
      description = "PrismNet Software-Defined Networking Service";
      wantedBy = [ "multi-user.target" ];
      after = [ "network.target" "iam.service" "flaredb.service" "chainfire.service" ];
      wants = [ "iam.service" "flaredb.service" "chainfire.service" ];

      serviceConfig = {
        Type = "simple";
        User = "prismnet";
        Group = "prismnet";
        Restart = "on-failure";
        RestartSec = "10s";

        # State directory management
        StateDirectory = "prismnet";
        StateDirectoryMode = "0750";

        # Security hardening
        NoNewPrivileges = true;
        PrivateTmp = true;
        ProtectSystem = "strict";
        ProtectHome = true;
        ReadWritePaths = [ cfg.dataDir ];

        # Start command
        ExecStart = "${cfg.package}/bin/prismnet-server --config ${prismnetConfigFile}";
      };
    };
  };
}
