module Lattice
  module CLI
    # Thin wrapper around `crystal tool format` that accepts an optional path
    # and exits with a meaningful code so CI pipelines can use Lattice as the
    # single tool entry point instead of invoking `crystal` directly.
    class Fmt
      def self.run(args : Array(String)) : NoReturn
        path = args.first? || "."

        unless File.exists?(path) || Dir.exists?(path)
          STDERR.puts "lattice fmt: path not found: #{path}"
          exit 1
        end

        cmd = ["crystal", "tool", "format", path]

        status = Process.run(
          cmd.first,
          args: cmd[1..],
          input: Process::Redirect::Inherit,
          output: Process::Redirect::Inherit,
          error: Process::Redirect::Inherit,
        )

        if status.success?
          exit 0
        else
          code = status.exit_code
          STDERR.puts "lattice fmt: crystal tool format exited with code #{code}"
          exit code
        end
      end
    end
  end
end
