{-# OPTIONS_GHC -Wall -Werror #-}

{-# LANGUAGE NoGeneralizedNewtypeDeriving #-}
{-# LANGUAGE Safe                         #-}

--------------------------------------------------------------------------------

-- |
-- Copyright  : (c) 2026 SPISE MISU ApS
-- License    : SSPL-1.0 OR AGPL-3.0-only
-- Maintainer : SPISE MISU <mail+hackage@spisemisu.com>
-- Stability  : experimental

--------------------------------------------------------------------------------

module Agent.Data.JSON
  ( -- * Infer JSON from Data
    Data
    -- * JSON Encoder/Decoder
  , DecodeError(InvalidJSON, DiffSchema)
  , encode
  , decode
  )
where

--------------------------------------------------------------------------------

import           Data.Data                            ( Data )

import           Internal.GaloisInc.Text.JSON.Generic
  ( Result (Error, Ok)
  , encodeJSON
  , fromJSON
  )
import           Internal.GaloisInc.Text.JSON.String
  ( readJSValue
  , runGetJSON
  )

--------------------------------------------------------------------------------

data DecodeError
  = InvalidJSON
  | DiffSchema

--------------------------------------------------------------------------------

encode
  :: Data a
  => a
  -> String
encode :: forall a. Data a => a -> String
encode = a -> String
forall a. Data a => a -> String
encodeJSON

decode
  :: Data a
  => String
  -> Either DecodeError a
decode :: forall a. Data a => String -> Either DecodeError a
decode String
json =
  case GetJSON JSValue -> String -> Either String JSValue
forall a. GetJSON a -> String -> Either String a
runGetJSON GetJSON JSValue
readJSValue String
json of
    Left  String
_ -> DecodeError -> Either DecodeError a
forall a b. a -> Either a b
Left DecodeError
InvalidJSON
    Right JSValue
v ->
      case JSValue -> Result a
forall a. Data a => JSValue -> Result a
fromJSON JSValue
v of
        Error String
_ -> DecodeError -> Either DecodeError a
forall a b. a -> Either a b
Left  DecodeError
DiffSchema
        Ok    a
a -> a -> Either DecodeError a
forall a b. b -> Either a b
Right a
a