import Config

if config_env() == :prod do
  config :safe_core, :license, System.get_env("SAFE_LICENSE")
end

# This section ensures that SAFE puts its data in a project-specific directory
# if SAFE is run from a directory `foo`, the data will be stored in `~/.safe/data/foo-<hash>`.
# Special case: if the directory is named `safe` (e.g. SAFE runs as a plugin inside a `safe/`
# subfolder), git root detection is attempted so the cache name reflects the actual project.

safe_dir =
  System.user_home()
  |> Path.join(".safe")
  |> Path.join("data")

{base_path, basename} =
  case File.cwd() do
    {:ok, cwd} ->
      resolved =
        if Path.basename(cwd) == "safe" && System.find_executable("git") do
          case System.cmd("git", ["rev-parse", "--show-toplevel"],
                 cd: cwd,
                 stderr_to_stdout: true
               ) do
            {root, 0} -> String.trim(root)
            _ -> cwd
          end
        else
          cwd
        end

      {resolved, Path.basename(resolved)}

    {:error, _} ->
      {nil, nil}
  end

project =
  case base_path do
    nil ->
      date = DateTime.utc_now() |> DateTime.to_string() |> String.replace(~r/[:\s]/, "-")
      "noname-#{date}"

    path ->
      hash =
        :sha
        |> :crypto.hash(path)
        |> Base.encode16(case: :lower)
        |> String.slice(0, 7)

      "#{basename}-#{hash}"
  end

project_dir = Path.join(safe_dir, project)
File.mkdir_p!(project_dir)

if config_env() in [:dev, :prod] do
  IO.puts(IO.ANSI.format([:light_black, "SAFE project dir: ", project_dir, :reset]))
end

config :logger, :default_handler, config: [file: ~c"#{project_dir}/logs/debug.log"]

config :mnesia, dir: ~c"#{project_dir}/data"

config :referl_core,
  scanner_tab_path: Path.join(project_dir, "safe_scanner.tab")
