{-# LANGUAGE UndecidableSuperClasses #-}

-- | Primitives supplying entrypoints declarations and lookup.
module Lorentz.EntryPoints.Core
  ( CanHaveEntryPoints
  , EntryPointsDerivation (..)
  , EpConstructionRes (..)
  , RequireAllUniqueEntryPoints
  , ParameterHasEntryPoints (..)
  , ParameterDeclaresEntryPoints
  , GetParameterEpDerivation
  , pepNotes
  , pepCall
  , AllParameterEntryPoints
  , LookupParameterEntryPoint
  , parameterEntryPointsToNotes
  , GetEntryPointArg
  , parameterEntryPointCall
  , GetDefaultEntryPointArg
  , parameterEntryPointCallDefault
  , flattenEntryPoints
  , ForbidExplicitDefaultEntryPoint
  , NoExplicitDefaultEntryPoint
  , sepcCallRootChecked
  , EntryPointRef (..)
  , NiceEntryPointName
  , eprName
  , GetEntryPointArgCustom
  , TrustEpName (..)
  , HasEntryPointArg (..)
  , HasDefEntryPointArg
  , parameterEntryPointCallCustom
  , EpdNone

    -- * Internals
  , RequireAllUniqueEntryPoints'
  ) where

import Data.Constraint (Dict(..), (\\))
import qualified Data.Kind as Kind
import Data.Map (Map, insert)
import Data.Singletons (SingI, sing)
import Data.Typeable (typeRep)
import Data.Vinyl.Derived (Label)
import Fcf (Eval, Exp)
import qualified Fcf
import qualified Fcf.Utils as Fcf
import Fmt (pretty)

import Michelson.Typed
import qualified Michelson.Untyped as U
import Util.Type
import Util.TypeLits

import Lorentz.Constraints.Scopes
import Lorentz.EntryPoints.Helpers

-- | Defines a generalized way to declare entrypoints for various parameter types.
--
-- When defining instances of this typeclass, set concrete @deriv@ argument
-- and leave variable @cp@ argument.
-- Also keep in mind, that in presence of explicit default entrypoint, all other
-- 'Or' arms should be callable, though you can put this burden on user if very
-- necessary.
class EntryPointsDerivation deriv cp where
  -- | Name and argument of each entrypoint.
  -- This may include intermediate ones, even root if necessary.
  --
  -- Touching this type family is costly (@O(N^2)@), don't use it often.
  type EpdAllEntryPoints deriv cp :: [(Symbol, Kind.Type)]

  -- | Get entrypoint argument by name.
  type EpdLookupEntryPoint deriv cp :: Symbol -> Exp (Maybe Kind.Type)

  -- | Construct parameter annotations corresponding to expected entrypoints set.
  --
  -- This method is implementation detail, for actual notes construction
  -- use 'parameterEntryPointsToNotes'.
  --
  -- TODO [#35]: Should also return field annotation
  epdNotes :: Notes (ToT cp)

  -- | Construct entrypoint caller.
  --
  -- This does not treat calls to default entrypoint in a special way.
  --
  -- This method is implementation detail, for actual entrypoint lookup
  -- use 'parameterEntryPointCall'.
  epdCall
    :: (KnownSymbol name, ParameterScope (ToT cp))
    => Label name
    -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntryPoint deriv cp name))

type RequireAllUniqueEntryPoints' deriv cp =
  RequireAllUnique
    "entrypoint name"
    (Eval (Fcf.Map Fcf.Fst $ EpdAllEntryPoints deriv cp))

-- | Ensure that all declared entrypoints are unique.
type RequireAllUniqueEntryPoints cp =
  RequireAllUniqueEntryPoints' (ParameterEntryPointsDerivation cp) cp

-- | Result of entrypoint lookup at term level.
data EpConstructionRes (param :: T) (marg :: Maybe Kind.Type) where
  EpConstructed
    :: ParameterScope (ToT arg)
    => EpLiftSequence (ToT arg) param -> EpConstructionRes param ('Just arg)
  EpConstructionFailed
    :: EpConstructionRes param 'Nothing

-- | Which entrypoints given parameter declares.
--
-- Note that usually this function should not be used as constraint, use
-- 'ParameterDeclaresEntryPoints' for this purpose.
class ( EntryPointsDerivation (ParameterEntryPointsDerivation cp) cp
      , RequireAllUniqueEntryPoints cp
      ) =>
      ParameterHasEntryPoints cp where
  type ParameterEntryPointsDerivation cp :: Kind.Type

-- | Parameter declares some entrypoints.
--
-- This is a version of 'ParameterHasEntryPoints' which we actually use in
-- constraints. When given type is a sum type or newtype, we refer to
-- 'ParameterHasEntryPoints' instance, otherwise this instance is not
-- necessary.
type ParameterDeclaresEntryPoints cp =
  ( If (CanHaveEntryPoints cp)
     (ParameterHasEntryPoints cp)
     (() :: Constraint)
  , NiceParameter cp
  , EntryPointsDerivation (GetParameterEpDerivation cp) cp
  )

-- | Version of 'ParameterEntryPointsDerivation' which we actually use in
-- function signatures. When given type is sum type or newtype, we refer to
-- 'ParameterEntryPointsDerivation', otherwise we suppose that no entrypoints
-- are declared.
type GetParameterEpDerivation cp =
  If (CanHaveEntryPoints cp)
     (ParameterEntryPointsDerivation cp)
     EpdNone

-- | Version of 'epdNotes' which we actually use in code.
-- It hides derivations stuff inside, and treats primitive types specially
-- like 'GetParameterEpDerivation' does.
pepNotes :: forall cp. ParameterDeclaresEntryPoints cp => Notes (ToT cp)
pepNotes = epdNotes @(GetParameterEpDerivation cp) @cp

-- | Version of 'epdCall' which we actually use in code.
-- It hides derivations stuff inside, and treats primitive types specially
-- like 'GetParameterEpDerivation' does.
pepCall
  :: forall cp name deriv.
     ( ParameterDeclaresEntryPoints cp, ParameterScope (ToT cp)
     , KnownSymbol name, deriv ~ GetParameterEpDerivation cp
     )
  => Label name
  -> EpConstructionRes (ToT cp) (Eval (EpdLookupEntryPoint deriv cp name))
pepCall = epdCall @(GetParameterEpDerivation cp) @cp

-- Derived methods and type families
----------------------------------------------------------------------------

-- | Get all entrypoints declared for parameter.
type family AllParameterEntryPoints (cp :: Kind.Type)
             :: [(Symbol, Kind.Type)] where
  AllParameterEntryPoints cp =
    EpdAllEntryPoints (GetParameterEpDerivation cp) cp

-- | Lookup for entrypoint type by name.
--
-- Does not treat default entrypoints in a special way.
type family LookupParameterEntryPoint (cp :: Kind.Type)
             :: Symbol -> Exp (Maybe Kind.Type) where
  LookupParameterEntryPoint cp =
    EpdLookupEntryPoint (GetParameterEpDerivation cp) cp

-- | Derive annotations for given parameter.
parameterEntryPointsToNotes
  :: forall cp.
     (Typeable cp, ParameterDeclaresEntryPoints cp)
  => ParamNotes (ToT cp)
parameterEntryPointsToNotes =
  let notes = pepNotes @cp
  in case mkParamNotes notes of
       -- Normally this should be valid because
       -- 1. Constraint in superclass of 'ParameterHasEntryPoints' ensures that
       -- no entrypoint is duplicated.
       -- 2. Each entrypoint is callable by laws of 'EntryPointsDerivation'.
       Right n -> n
       Left e -> error $ mconcat
        [ "Lorentz unexpectedly compiled into contract with \
          \illegal parameter declaration.\n"
        , "Parameter: " <> show (typeRep (Proxy @cp)) <> "\n"
        , "Derived annotations: " <> show notes <> "\n"
        , "Failure reason: " <> pretty e
        ]

-- | Prepare call to given entrypoint.
--
-- This does not treat calls to default entrypoint in a special way.
-- To call default entrypoint properly use 'parameterEntryPointCallDefault'.
parameterEntryPointCall
  :: forall cp name.
     ( ParameterDeclaresEntryPoints cp
     , KnownSymbol name
     )
  => Label name
  -> EntryPointCall cp (GetEntryPointArg cp name)
parameterEntryPointCall label =
  withDict (niceParameterEvi @cp) $
  case pepCall @cp label of
    EpConstructed liftSeq -> EntryPointCall
      { epcName = epNameFromParamAnn (ctorNameToAnn @name)
               ?: error "Empty constructor-entrypoint name"
      , epcParamProxy = Proxy
      , epcLiftSequence = liftSeq
      }
    EpConstructionFailed ->
      -- Not possible by 'GetEntryPointArg' constraint.
      error "impossible"

-- | Get type of entrypoint with given name, fail if not found.
type GetEntryPointArg cp name = Eval
  ( Fcf.LiftM2
      Fcf.FromMaybe
      (Fcf.TError ('Text "Entrypoint not found: " ':<>: 'ShowType name ':$$:
                   'Text "In contract parameter `" ':<>: 'ShowType cp ':<>: 'Text "`"))
      (LookupParameterEntryPoint cp name)
  )

type DefaultEpName = "Default"

-- | Call the default entrypoint.
parameterEntryPointCallDefault
  :: forall cp.
     (ParameterDeclaresEntryPoints cp)
  => EntryPointCall cp (GetDefaultEntryPointArg cp)
parameterEntryPointCallDefault =
  withDict (niceParameterEvi @cp) $
  case pepCall @cp (fromLabel @DefaultEpName) of
    EpConstructed liftSeq -> EntryPointCall
      { epcName = DefEpName
      , epcParamProxy = Proxy
      , epcLiftSequence = liftSeq
      }
    EpConstructionFailed ->
      EntryPointCall
      { epcName = DefEpName
      , epcParamProxy = Proxy
      , epcLiftSequence = EplArgHere
      }

-- | Get type of entrypoint with given name, fail if not found.
type GetDefaultEntryPointArg cp = Eval
  ( Fcf.LiftM2
      Fcf.FromMaybe
      (Fcf.Pure cp)
      (LookupParameterEntryPoint cp DefaultEpName)
  )

-- | Ensure that there is no explicit "default" entrypoint.
type ForbidExplicitDefaultEntryPoint cp = Eval
  (Fcf.LiftM3
      Fcf.UnMaybe
      (Fcf.Pure (Fcf.Pure (() :: Constraint)))
      (Fcf.TError
         ('Text "Parameter used here must have no explicit \"default\" entrypoint" ':$$:
          'Text "In parameter type `" ':<>: 'ShowType cp ':<>: 'Text "`"
         )
      )
      (LookupParameterEntryPoint cp DefaultEpName)
  )

-- | Similar to 'ForbidExplicitDefaultEntryPoint', but in a version which
-- the compiler can work with (and which produces errors confusing for users :/)
type NoExplicitDefaultEntryPoint cp =
  Eval (LookupParameterEntryPoint cp DefaultEpName) ~ 'Nothing

-- | Call root entrypoint safely.
sepcCallRootChecked
  :: forall cp.
     (NiceParameter cp, ForbidExplicitDefaultEntryPoint cp)
  => SomeEntryPointCall cp
sepcCallRootChecked = sepcCallRootUnsafe \\ niceParameterEvi @cp
  where
    -- Avoiding redundant-constraints warning.
    _validUsage = Dict @(ForbidExplicitDefaultEntryPoint cp)

-- | Which entrypoint to call.
--
-- We intentionally distinguish default and non-default cases because
-- this makes API more details-agnostic.
data EntryPointRef (mname :: Maybe Symbol) where
  -- | Call the default entrypoint, or root if no explicit default is assigned.
  CallDefault :: EntryPointRef 'Nothing

  -- | Call the given entrypoint; calling default is not treated specially.
  -- You have to provide entrypoint name via passing it as type argument.
  --
  -- Unfortunatelly, here we cannot accept a label because in most cases our
  -- entrypoints begin from capital letter (being derived from constructor name),
  -- while labels must start from a lower-case letter, and there is no way to
  -- make a conversion at type-level.
  Call :: NiceEntryPointName name => EntryPointRef ('Just name)

-- | Constraint on type-level entrypoint name specifier.
type NiceEntryPointName name = (KnownSymbol name, ForbidDefaultName name)

type family ForbidDefaultName (name :: Symbol) :: Constraint where
  ForbidDefaultName "Default" =
    TypeError ('Text "Calling `Default` entrypoint is not allowed here")
  ForbidDefaultName _ = ()

eprName :: forall mname. EntryPointRef mname -> EpName
eprName = \case
  CallDefault -> DefEpName
  Call | (_ :: Proxy ('Just name)) <- Proxy @mname ->
    epNameFromParamAnn (ctorNameToAnn @name)
    ?: error "Empty constructor-entrypoint name"

-- | Universal entrypoint calling.
parameterEntryPointCallCustom
  :: forall cp mname.
     (ParameterDeclaresEntryPoints cp)
  => EntryPointRef mname
  -> EntryPointCall cp (GetEntryPointArgCustom cp mname)
parameterEntryPointCallCustom = \case
  CallDefault ->
    parameterEntryPointCallDefault @cp
  Call | (_ :: Proxy ('Just name)) <- Proxy @mname ->
    parameterEntryPointCall @cp (fromLabel @name)

-- | Flatten a provided list of notes to a map of its entrypoints
-- and its corresponding utype.
--
-- It is obtained by constructing `insert k1 v1 (insert k2 v2 ... mempty)`
-- pipe using `Endo` so that it is more concise rather than stacking composition
-- of monoidal endomorphisms explicitly. Note that here no duplicates can appear
-- in returned map for `ParamNotes` even if they may appear inside passed `Notes` tree.
flattenEntryPoints :: SingI t => ParamNotes t -> Map EpName U.Type
flattenEntryPoints (unParamNotes -> notes) = appEndo (gatherEPs (sing, notes)) mempty
  where
    gatherEPs
      :: forall n.
         (Sing n, Notes n)
      -> Endo (Map EpName U.Type)
    gatherEPs = \case
      (STOr ls rs, NTOr _ fn1 fn2 ln rn) -> mconcat
        [ Endo . maybe id (uncurry insert) . psi ln $ epNameFromParamAnn fn1
        , Endo . maybe id (uncurry insert) . psi rn $ epNameFromParamAnn fn2
        , gatherEPs (ls, ln)
        , gatherEPs (rs, rn)
        ]
      _ -> mempty

    psi
      :: forall n.
         SingI n
      => Notes n
      -> Maybe EpName
      -> Maybe (EpName, U.Type)
    psi n x = tensor x $ mkUType sing n

    -- Tensorial strength criteria
    tensor :: Functor f => f a -> b -> f (a,b)
    tensor fa b = fmap (,b) fa

-- | Universal entrypoint lookup.
type family GetEntryPointArgCustom cp mname :: Kind.Type where
  GetEntryPointArgCustom cp 'Nothing = GetDefaultEntryPointArg cp
  GetEntryPointArgCustom cp ('Just name) = GetEntryPointArg cp name

----------------------------------------------------------------------------
-- Type class for functions that take entrypoint name as argument
----------------------------------------------------------------------------

-- | When we call a Lorentz contract we should pass entrypoint name
-- and corresponding argument. Ideally we want to statically check
-- that parameter has entrypoint with given name and
-- argument. Constraint defined by this type class holds for contract
-- with parameter @cp@ that have entrypoint matching @name@ with type
-- @arg@.
--
-- In order to check this property statically, we need to know entrypoint
-- name in compile time, 'EntryPointRef' type serves this purpose.
-- If entrypoint name is not known, one can use 'TrustEpName' wrapper
-- to take responsibility for presence of this entrypoint.
--
-- If you want to call a function which has this constraint, you have
-- two options:
-- 1. Pass contract parameter @cp@ using type application, pass 'EntryPointRef'
-- as a value and pass entrypoint argument. Type system will check that
-- @cp@ has an entrypoint with given reference and type.
-- 2. Pass 'EpName' wrapped into 'TrustEpName' and entrypoint argument.
-- In this case passing contract parameter is not necessary, you do not even
-- have to know it.
class HasEntryPointArg cp name arg where
  -- | Data returned by this method may look somewhat arbitrary.
  -- 'EpName' is obviously needed because @name@ can be
  -- 'EntryPointRef' or 'TrustEpName'.  @Dict@ is returned because in
  -- 'EntryPointRef' case we get this evidence for free and don't want
  -- to use it. We seem to always need it anyway.
  useHasEntryPointArg :: name -> (Dict (ParameterScope (ToT arg)), EpName)

-- | 'HasEntryPointArg' constraint specialized to default entrypoint.
type HasDefEntryPointArg cp defEpName defArg =
  ( defEpName ~ EntryPointRef 'Nothing
  , HasEntryPointArg cp defEpName defArg
  )

instance
  (GetEntryPointArgCustom cp mname ~ arg, ParameterDeclaresEntryPoints cp) =>
  HasEntryPointArg cp (EntryPointRef mname) arg where
  useHasEntryPointArg epRef =
    withDict (niceParameterEvi @cp) $
    case parameterEntryPointCallCustom @cp epRef of
      EntryPointCall{} -> (Dict, eprName epRef)

-- | This wrapper allows to pass untyped 'EpName' and bypass checking
-- that entrypoint with given name and type exists.
newtype TrustEpName = TrustEpName EpName

instance (NiceParameter arg) =>
  HasEntryPointArg cp TrustEpName arg where
  useHasEntryPointArg (TrustEpName epName) = (Dict, epName) \\ niceParameterEvi @arg

----------------------------------------------------------------------------
-- Trivial implementation
----------------------------------------------------------------------------

-- | No entrypoints declared, parameter type will serve as argument type
-- of the only existing entrypoint (default one).
data EpdNone
instance SingI (ToT cp) => EntryPointsDerivation EpdNone cp where
  type EpdAllEntryPoints EpdNone cp = '[]
  type EpdLookupEntryPoint EpdNone cp = Fcf.ConstFn 'Nothing
  epdNotes = starNotes
  epdCall _ = EpConstructionFailed