{-
-- EPITECH PROJECT, 2026
-- Glados
-- File description:
-- File
-}

module Common.Utils.Bytecode.File
    ( getFileContent
    , tryReadFile
    ) where

import qualified Data.ByteString as BS
import Control.Exception (try, SomeException)
import System.Exit (exitWith, ExitCode(..))

-- | Helper to attempt reading a file with explicit typing.
--
-- @details
--   Moves the type casting out of the main logic.
--
tryReadFile :: String -> IO (Either SomeException BS.ByteString)
tryReadFile :: String -> IO (Either SomeException ByteString)
tryReadFile String
path = IO ByteString -> IO (Either SomeException ByteString)
forall e a. Exception e => IO a -> IO (Either e a)
try (String -> IO ByteString
BS.readFile String
path)

-- | Retrieves the file content or exits the program on error.
--
-- @args
--   - path: Path to the file.
--
-- @details
--   Handles the IO exception immediately: prints the error and calls exitFailure.
--   This prevents 'executeFile' from handling nested cases.
--
-- @return
--   The file content as ByteString.
--
getFileContent :: String -> IO BS.ByteString
getFileContent :: String -> IO ByteString
getFileContent String
path = do
    result <- String -> IO (Either SomeException ByteString)
tryReadFile String
path
    case result of
        Left SomeException
err -> String -> IO ()
putStrLn (String
"\ESC[31mIO Error:\ESC[0m " String -> String -> String
forall a. [a] -> [a] -> [a]
++ SomeException -> String
forall a. Show a => a -> String
show SomeException
err) IO () -> IO ByteString -> IO ByteString
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
            ExitCode -> IO ByteString
forall a. ExitCode -> IO a
exitWith (Int -> ExitCode
ExitFailure Int
84)
        Right ByteString
content -> ByteString -> IO ByteString
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ByteString
content