-- | This module contains functionality related to computing a "unique type guid lookup" function, which resolves a
-- name to a unique type's GUID to reuse.
module Unison.Cli.UniqueTypeGuidLookup
  ( loadUniqueTypeGuid,
  )
where

import U.Codebase.Branch qualified as Codebase.Branch
import Unison.Codebase qualified as Codebase
import Unison.Codebase.Path qualified as Path
import Unison.Codebase.ProjectPath (ProjectPath)
import Unison.Codebase.ProjectPath qualified as PP
import Unison.Codebase.UniqueTypeGuidLookup qualified as Codebase
import Unison.Name (Name)
import Unison.Prelude
import Unison.Sqlite qualified as Sqlite

loadUniqueTypeGuid :: ProjectPath -> Name -> Sqlite.Transaction (Maybe Text)
loadUniqueTypeGuid :: ProjectPath -> Name -> Transaction (Maybe Text)
loadUniqueTypeGuid ProjectPath
pp Name
name0 = do
  let (Path
namePath, NameSegment
finalSegment) = Name -> (Path, NameSegment)
Path.splitFromName Name
name0
  let fullPP :: ProjectPath
fullPP = ProjectPath
pp ProjectPath -> (ProjectPath -> ProjectPath) -> ProjectPath
forall a b. a -> (a -> b) -> b
& ASetter ProjectPath ProjectPath Path Path
-> (Path -> Path) -> ProjectPath -> ProjectPath
forall s t a b. ASetter s t a b -> (a -> b) -> s -> t
over ASetter ProjectPath ProjectPath Path Path
forall p b (f :: * -> *).
Functor f =>
(Path -> f Path) -> ProjectPathG p b -> f (ProjectPathG p b)
PP.path_ (Path -> Path -> Path
forall a. Semigroup a => a -> a -> a
<> Path
namePath)

  -- Define an operation to load a branch by its full path from the root namespace.
  --
  -- This ought to probably lean somewhat on a cache (so long as the caller is aware of the cache, and discrads it at
  -- an appropriate time, such as after the current unison file finishes parsing).
  let loadBranchAtPath :: ProjectPath -> Sqlite.Transaction (Maybe (Codebase.Branch.Branch Sqlite.Transaction))
      loadBranchAtPath :: ProjectPath -> Transaction (Maybe (Branch Transaction))
loadBranchAtPath = ProjectPath -> Transaction (Maybe (Branch Transaction))
Codebase.getMaybeShallowBranchAtProjectPath

  (ProjectPath -> Transaction (Maybe (Branch Transaction)))
-> ProjectPath -> NameSegment -> Transaction (Maybe Text)
Codebase.loadUniqueTypeGuid ProjectPath -> Transaction (Maybe (Branch Transaction))
loadBranchAtPath ProjectPath
fullPP NameSegment
finalSegment