{-|
Module      : Gargantext.Core.Config.Utils
Description :
Copyright   : (c) CNRS, 2024-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX

-}

module Gargantext.Core.Config.Utils (
    readConfig
  )
  where

import Gargantext.Core.Config.Types (SettingsFile(..))
import Gargantext.Prelude
import Toml
import Gargantext.Core.Config
import System.Environment (lookupEnv)
import Gargantext.System.Logging.Types (parseLogLevel)
import qualified Data.Text as T


readConfig :: SettingsFile -> IO GargConfig
readConfig (SettingsFile fp) = do
  c <- readFile fp

  case decode c of
    Failure err -> panicTrace ("Error reading TOML file: " <> show err)
    Success _ r -> do
      -- Ovverride the log level based on the GGTX_LOG_LEVEL (if set)
      mLvl <- lookupEnv "GGTX_LOG_LEVEL"
      case mLvl of
        Nothing      -> pure r
        Just s       ->
          case parseLogLevel (T.pack s) of
            Left err   -> do
              putStrLn $ "unknown log level " <> s <> ": " <> T.unpack err <> " , ignoring GGTX_LOG_LEVEL"
              pure r
            Right lvl' -> pure $ r & gc_logging . lc_log_level .~ lvl'
