require "file_utils"

module Lattice
  module CLI
    # Scaffolds a minimal `.lattice.yml` configuration file in the current
    # working directory (or a specified project root).
    class Init
      DEFAULT_CONFIG = <<-YAML
        # .lattice.yml — Lattice LSP configuration
        # See https://codeberg.org/DaZhi-the-Revelator/lattice for documentation.

        # Path(s) to Crystal source roots (relative to this file).
        source_dirs:
          - src

        # Path to the ameba binary used for linting (leave blank to auto-detect).
        ameba_path: ""

        # Enable strict type-checking mode.
        strict_mode: false

        # Cache directory for the persistent symbol index.
        cache_dir: .lattice-cache

        # Logging level: debug | info | warn | error
        log_level: warn
        YAML

      def self.run(dir : String = ".") : NoReturn
        config_path = File.join(dir, ".lattice.yml")

        if File.exists?(config_path)
          STDERR.puts "lattice init: '#{config_path}' already exists — not overwriting."
          STDERR.puts "Delete it first or edit it manually."
          exit 1
        end

        FileUtils.mkdir_p(dir) unless File.directory?(dir)
        File.write(config_path, DEFAULT_CONFIG.gsub(/^        /, ""))

        puts "Created #{config_path}"
        puts "Edit it to match your project layout, then start Lattice."
        exit 0
      end
    end
  end
end
