{ pkgs, ... }:

let
  sshKeyPath = "/home/lebowski/.ssh/id_ed25519";
  sshKeyName = "V3";
  serverName = "nix-builder";
  serverType = "ccx43";
  location = "nbg1";

  sshCmd = "ssh -o StrictHostKeyChecking=no -o BatchMode=yes -i ${sshKeyPath}";

  # Spin up a builder from the NixOS snapshot
  builder-up = pkgs.writeShellApplication {
    name = "builder-up";
    runtimeInputs = with pkgs; [ hcloud openssh ];
    text = ''
      SERVER_NAME="${serverName}"
      SSH_KEY_PATH="${sshKeyPath}"

      # ── Check if server already exists ──
      if hcloud server describe "$SERVER_NAME" &>/dev/null; then
        IP=$(hcloud server ip "$SERVER_NAME")
        echo "Server '$SERVER_NAME' already running at $IP"
        echo "  builder-ssh"
        exit 0
      fi

      # ── Find snapshot ──
      SNAPSHOT_ID=$(hcloud image list --type snapshot --selector description="${snapshotDesc}" -o noheader -o columns=id 2>/dev/null | head -1)
      if [ -z "$SNAPSHOT_ID" ]; then
        # Fallback: search by description
        SNAPSHOT_ID=$(hcloud image list --type snapshot -o noheader -o columns=id,description | grep "${snapshotDesc}" | awk '{print $1}' | head -1)
      fi

      if [ -z "$SNAPSHOT_ID" ]; then
        echo "ERROR: No snapshot '${snapshotDesc}' found."
        echo "  Create one with: builder-snapshot"
        exit 1
      fi

      # ── Create server from snapshot ──
      echo "==> Creating ${serverType} in ${location} from snapshot $SNAPSHOT_ID..."
      hcloud server create \
        --name "$SERVER_NAME" \
        --type "${serverType}" \
        --image "$SNAPSHOT_ID" \
        --location "${location}" \
        --label role=nix-builder \
        --ssh-key "${sshKeyName}"

      IP=$(hcloud server ip "$SERVER_NAME")

      # ── Wait for SSH ──
      echo "==> Waiting for SSH..."
      for i in $(seq 1 30); do
        if ${sshCmd} "root@''${IP}" true 2>/dev/null; then
          break
        fi
        if [ "$i" -eq 30 ]; then
          echo "ERROR: SSH did not become available after 150s"
          exit 1
        fi
        sleep 5
      done

      # ── Update known_hosts ──
      ssh-keygen -R "$IP" 2>/dev/null || true
      ssh-keyscan -H "$IP" >> ~/.ssh/known_hosts 2>/dev/null

      echo ""
      echo "=== Builder ready ==="
      echo "  builder-ssh"
    '';
  };

  # SSH into the builder
  builder-ssh = pkgs.writeShellApplication {
    name = "builder-ssh";
    runtimeInputs = with pkgs; [ hcloud openssh ];
    text = ''
      SERVER_NAME="${serverName}"
      SSH_KEY_PATH="${sshKeyPath}"

      if ! hcloud server describe "$SERVER_NAME" &>/dev/null; then
        echo "No server '$SERVER_NAME' found. Run builder-up first."
        exit 1
      fi

      IP=$(hcloud server ip "$SERVER_NAME")
      ssh -i "$SSH_KEY_PATH" -t "root@$IP" "tmux new-session -A -s build"
    '';
  };

  # Tear down the builder
  builder-down = pkgs.writeShellApplication {
    name = "builder-down";
    runtimeInputs = with pkgs; [ hcloud openssh ];
    text = ''
      SERVER_NAME="${serverName}"

      if hcloud server describe "$SERVER_NAME" &>/dev/null; then
        IP=$(hcloud server ip "$SERVER_NAME")
        echo "==> Deleting '$SERVER_NAME' ($IP)..."
        hcloud server delete "$SERVER_NAME"
        ssh-keygen -R "$IP" 2>/dev/null || true
        echo "    Done."
      else
        echo "No server '$SERVER_NAME' found."
      fi
    '';
  };

in
{
  environment.systemPackages = [
    builder-up
    builder-ssh
    builder-down
    pkgs.hcloud
  ];
}
