{ config, containerCfg, pkgs, lib, builder, name, ... }:
let 
  serverCfg = config.syscfg.server;
  
  # Ensure the package is available (Nixpkgs includes frigate)
  frigatePkg = pkgs.frigate;

  image = pkgs.dockerTools.streamLayeredImage {
    name = "frigate";
    tag = frigatePkg.version;
    contents = [ 
      pkgs.bashInteractive 
      frigatePkg
      pkgs.ffmpeg # Explicitly included for video stream processing
    ];
    config = {
      Entrypoint = [ "${frigatePkg}/bin/frigate" ];
      Cmd = [ "start" ];
      ExposedPorts = {
        "5000/tcp" = {}; # Web UI / API
        "8554/tcp" = {}; # RTSP Feeds
        "8555/tcp" = {}; # WebRTC
      };
      Env = [
        "FRIGATE_RTSP_PASSWORD=secret" # Base fallback, overridden by envFile/sops
      ];
    };
  };
in {
  requires.secrets = [ name ];

  runtime = {
    paths = [
      {
        path = "${serverCfg.path.config.path}/frigate/";
        mode = "0755";
      }
      {
        path = "/var/lib/frigate/storage/";
        mode = "0755"; # Dedicated path for heavy video recordings and media
      }
    ];

    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        imageStream = image;
        port = 5000;
        secret = name;
        extraEnv = {
          PLUS_API_KEY = ""; # Optional: For Frigate Plus users
        };
        overrides = {
          cmd = [ ];
          volumes = [
            "${serverCfg.path.config.path}/frigate:/config"
            "/var/lib/frigate/storage:/media/frigate"
            "/dev/bus/usb:/dev/bus/usb" # Passes Google Coral USB TPU to the container
            "/dev/dri:/dev/dri"         # Passes Intel/AMD GPU for hardware video decoding
          ];
        };
      };
    };

    setup = {
      trigger = "server";
      envFile = config.sops.secrets."FRIGATE_ENV".path;
      script = pkgs.writeShellScript "setup-frigate" ''
        mkdir -p "${serverCfg.path.config.path}/frigate"
        mkdir -p "/var/lib/frigate/storage"
        
        # Bootstrap a standard configuration layout if missing
        if [ ! -f "${serverCfg.path.config.path}/frigate/config.yml" ]; then
          cat <<EOF > "${serverCfg.path.config.path}/frigate/config.yml"
mqtt:
  enabled: False # Set to True and define host if connecting to Home Assistant

database:
  path: /config/frigate.db

cameras:
  dummy_camera: # Replace with your actual RTSP stream details
    enabled: false
    ffmpeg:
      inputs:
        - path: rtsp://127.0.0.1:554/live
          roles:
            - detect
    detect:
      enabled: false
EOF
        fi
      '';
    };
  };
}
