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

with lib;

let
  cfg = config.nix-nos.bgp;

  # Generate BIRD2 configuration
  birdConfig = pkgs.writeText "bird.conf" ''
    # BIRD2 BGP configuration (Nix-NOS generated)

    router id ${cfg.routerId};

    # Define routing tables
    protocol kernel {
      ipv4 {
        export all;
      };
      learn;
    }

    protocol device {
      scan time 10;
    }

    # BGP protocol definitions
    ${concatMapStringsSep "\n" (peer: ''
      protocol bgp peer_${replaceStrings ["."] ["_"] peer.address} {
        description "${if peer.description != "" then peer.description else "BGP peer ${peer.address}"}";
        local as ${toString cfg.asn};
        neighbor ${peer.address} as ${toString peer.asn};

        ipv4 {
          import all;
          export where source = RTS_STATIC;
        };
      }
    '') cfg.peers}

    # Static routes for announcements
    protocol static {
      ipv4;
      ${concatMapStringsSep "\n" (ann: ''
        route ${ann.prefix} ${if ann.nexthop != null then "via ${ann.nexthop}" else "blackhole"};
      '') cfg.announcements}
    }
  '';

in {
  config = mkIf (config.nix-nos.enable && cfg.enable && cfg.backend == "bird") {
    # Install BIRD2 package
    environment.systemPackages = [ pkgs.bird ];

    # BIRD2 systemd service
    systemd.services.bird = {
      description = "BIRD Internet Routing Daemon";
      after = [ "network.target" ];
      wantedBy = [ "multi-user.target" ];

      serviceConfig = {
        Type = "forking";
        ExecStart = "${pkgs.bird}/bin/bird -c ${birdConfig}";
        ExecReload = "${pkgs.bird}/bin/birdc configure";
        Restart = "on-failure";
        RestartSec = "5s";
      };
    };

    # Enable IP forwarding for BGP
    boot.kernel.sysctl = {
      "net.ipv4.ip_forward" = 1;
    };
  };
}
