{-# LANGUAGE OverloadedStrings #-} -- needed for aeson
{-# LANGUAGE DeriveGeneric #-}
--{-# LANGUAGE DeriveAnyClass #-}
--{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}

module Embeddings where
 
 import System.IO -- for IO
 
 import Network.Curl -- for the cURL system
 import Network.Curl.Opts
 import Network.Curl.Code
 import Network.Curl.Easy
 import Foreign.C.String
 
 import Data.Aeson -- for the aeson system
 import Data.Aeson.Encode.Pretty
 import Data.Aeson.TH(deriveJSON, defaultOptions, Options(fieldLabelModifier)) -- needed for Template Haskell to rename types on the fly.
 import Data.List -- for intersperse
 import GHC.Generics
 import qualified Data.ByteString.Lazy.UTF8 as B
 
 import Data.Maybe
 
-- .........................

 data RetContent = RetContent {
 model :: Maybe String,
 embeddings :: Maybe [[Double]],
 total_duration :: Maybe Integer,
 load_duration :: Maybe Integer,
 prompt_eval_count :: Maybe Int
 } deriving (Generic,Show,Read)

 
 $(deriveJSON defaultOptions ''RetContent)

-- ==================================

 hoot :: String -> Maybe RetContent
 hoot xs = decode $ B.fromString xs
 
-- ==================================

 unJust :: Maybe a -> a
 unJust = fromJust

-- ==================================================

 getResponses :: String -> RetContent
 getResponses buf = unJust gablu
  where
   gablu = hoot buf
  --putStrLn $ "\naeson object formed:\n"

-- ===============================

 getEmbedding :: RetContent -> String
 getEmbedding buf = show vect
  where
   vect = ((unJust(embeddings buf))!!0)
  
-- =======================

 doQuery :: String -> IO RetContent
 doQuery punput = do
  handil <- initialize
  let url = "http://localhost:11434/api/embed"
  let model = "\"model\" : \"nomic-embed-text\""
  let input = "\"input\" : \"" ++ punput ++ "\""
  let postCargo = "{" ++ model ++ "," ++ input ++ "}"
  let setoptions = [CurlCustomRequest "POST", CurlPostFields [postCargo]]
  (code,buf) <- curlGetString url setoptions
  --putStrLn buf
  --let bufLines = lines buf
  --let buffet = concat $ intersperse "," bufLines
  --putStrLn tuffet
  return (getResponses buf)
  --print $ "JSON string received from openAI:\n"
  --let res = getResponses buf
  --let uttor = getReturnedContents res
  --print uttor
