{ pkgs, ... }:
let
  codexPackage = pkgs.runCommand "codex-0.2.0" { } ''
    mkdir -p $out/bin
    echo '#!/bin/sh' > $out/bin/codex
    chmod +x $out/bin/codex
  '';
in
{
  home.preferXdgDirectories = true;
  programs.codex = {
    enable = true;
    package = codexPackage;
    rules.default = ''
      prefix_rule(
        pattern = ["nix", "build"],
        decision = "allow",
        justification = "Allow local builds",
      )
    '';
    settings = {
      model = "gemma3:latest";
      model_provider = "ollama";
      model_providers = {
        ollama = {
          name = "Ollama";
          baseURL = "http://localhost:11434/v1";
          envKey = "OLLAMA_API_KEY";
        };
      };
    };
    context = ''
      - Always respond with emojis
      - Only use git commands when explicitly requested
    '';
  };
  nmt.script = ''
    assertFileContains home-path/etc/profile.d/hm-session-vars.sh \
      'export CODEX_HOME="/home/hm-user/.config/codex"'
    assertFileExists home-files/.config/codex/config.toml
    assertFileContent home-files/.config/codex/config.toml \
      ${./config.toml}
    assertFileExists home-files/.config/codex/AGENTS.md
    assertFileContent home-files/.config/codex/AGENTS.md \
      ${./AGENTS.md}
    assertFileExists home-files/.config/codex/rules/default.rules
    assertFileContent home-files/.config/codex/rules/default.rules \
      ${builtins.toFile "expected-xdg-default.rules" ''
        prefix_rule(
          pattern = ["nix", "build"],
          decision = "allow",
          justification = "Allow local builds",
        )
      ''}
  '';
}
