-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

-- | Resolve tagged registry endpoints and their CodeArtifact store identities.
module Ecluse.Config.Target (
    -- * Resolution
    resolveStoreBackend,
    resolveUploadBackend,
    resolvePrivateBackend,
    vetTargetTag,
    vetPrivateRepository,
    vetPublicationRepository,
    parseCodeArtifactHost,
    isAccountId,

    -- * Service credential presentation
    storePresentation,
) where

import Data.Char (isDigit)
import Data.Text qualified as T

import Ecluse.Config.Types (
    ConfigError (..),
    MirrorEndpoint (..),
    MirrorWrite (..),
    PublicationEndpoint (..),
    StoreBackend (..),
    StoreTag (..),
    Target (..),
 )
import Ecluse.Core.Ecosystem (Ecosystem)
import Ecluse.Core.Registry.Request (ServicePresentation, declaredPresentation, nativePresentation)
import Ecluse.Core.Security (hostAddress)
import Ecluse.Core.Security.Egress (RegistryUrl, registryUrlText)
import Ecluse.Core.Text (nonBlank, registryPath)
import Ecluse.Runtime.Credential.CodeArtifact (CodeArtifactConfig (..))
import Ecluse.Runtime.Credential.CodeArtifact.Presentation (codeArtifactAuthMechanism)
import Ecluse.Runtime.Maintenance.CodeArtifact.Decide (
    CodeArtifactStore (..),
    codeArtifactFormat,
    formatToken,
 )

-- | Resolve the read root and credential identity declared by a mirror target.
resolveStoreBackend :: Ecosystem -> MirrorEndpoint -> Either ConfigError StoreBackend
resolveStoreBackend :: Ecosystem -> MirrorEndpoint -> Either ConfigError StoreBackend
resolveStoreBackend = EndpointPurpose
-> Ecosystem -> MirrorEndpoint -> Either ConfigError StoreBackend
resolveMirrorBackend EndpointPurpose
RepositoryEndpoint

-- | Resolve a native upload endpoint without admitting upload paths as read roots.
resolveUploadBackend :: Ecosystem -> MirrorEndpoint -> RegistryUrl -> Either ConfigError StoreBackend
resolveUploadBackend :: Ecosystem
-> MirrorEndpoint -> RegistryUrl -> Either ConfigError StoreBackend
resolveUploadBackend Ecosystem
eco MirrorEndpoint
endpoint RegistryUrl
upload = EndpointPurpose
-> Ecosystem -> MirrorEndpoint -> Either ConfigError StoreBackend
resolveMirrorBackend EndpointPurpose
UploadEndpoint Ecosystem
eco MirrorEndpoint
endpoint{meUrl = upload}

data EndpointPurpose = RepositoryEndpoint | UploadEndpoint

resolveMirrorBackend :: EndpointPurpose -> Ecosystem -> MirrorEndpoint -> Either ConfigError StoreBackend
resolveMirrorBackend :: EndpointPurpose
-> Ecosystem -> MirrorEndpoint -> Either ConfigError StoreBackend
resolveMirrorBackend EndpointPurpose
purpose Ecosystem
eco MirrorEndpoint
endpoint = case MirrorEndpoint -> MirrorWrite
meWrite MirrorEndpoint
endpoint of
    WriteRegistry Secret
token -> StoreBackend -> Either ConfigError StoreBackend
forall a b. b -> Either a b
Right (Secret -> StoreBackend
BackendRegistry Secret
token)
    WriteVerdaccio Secret
token DeletionConsent
consent -> StoreBackend -> Either ConfigError StoreBackend
forall a b. b -> Either a b
Right (Secret -> DeletionConsent -> StoreBackend
BackendVerdaccio Secret
token DeletionConsent
consent)
    WriteCodeArtifact Maybe Natural
mDuration -> do
        (domain, owner, region) <- Ecosystem
-> Text -> RegistryUrl -> Either ConfigError (Text, Text, Text)
codeArtifactHost Ecosystem
eco Text
key (MirrorEndpoint -> RegistryUrl
meUrl MirrorEndpoint
endpoint)
        store <- codeArtifactStore purpose eco key (registryUrlText (meUrl endpoint)) domain owner region
        Right (BackendCodeArtifact (mintIdentity domain owner region mDuration) store)
  where
    key :: Text
key = case EndpointPurpose
purpose of
        EndpointPurpose
RepositoryEndpoint -> Text
mirrorTargetKey
        EndpointPurpose
UploadEndpoint -> Text
"mirrorTarget.codeArtifact.uploadUrl"

-- | Resolve a CodeArtifact private read root with the default token lifetime.
resolvePrivateBackend :: Ecosystem -> Target -> Either ConfigError (StoreBackend, CodeArtifactStore)
resolvePrivateBackend :: Ecosystem
-> Target -> Either ConfigError (StoreBackend, CodeArtifactStore)
resolvePrivateBackend Ecosystem
eco Target
target = do
    (domain, owner, region) <- Ecosystem
-> Text -> RegistryUrl -> Either ConfigError (Text, Text, Text)
codeArtifactHost Ecosystem
eco Text
privateUpstreamKey (Target -> RegistryUrl
tgtUrl Target
target)
    store <- codeArtifactStore RepositoryEndpoint eco privateUpstreamKey (registryUrlText (tgtUrl target)) domain owner region
    pure (BackendCodeArtifact (mintIdentity domain owner region Nothing) store, store)

-- | Check the host against its declared tag. Repository path checks belong to the endpoint role.
vetTargetTag :: Ecosystem -> Text -> Target -> Either ConfigError ()
vetTargetTag :: Ecosystem -> Text -> Target -> Either ConfigError ()
vetTargetTag Ecosystem
eco Text
key Target
target = case Target -> StoreTag
tgtTag Target
target of
    StoreTag
TagCodeArtifact -> Either ConfigError (Text, Text, Text) -> Either ConfigError ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Ecosystem
-> Text -> RegistryUrl -> Either ConfigError (Text, Text, Text)
codeArtifactHost Ecosystem
eco (Text
key Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
".codeArtifact.url") (Target -> RegistryUrl
tgtUrl Target
target))
    StoreTag
TagRegistry -> () -> Either ConfigError ()
forall a b. b -> Either a b
Right ()
    StoreTag
TagVerdaccio -> () -> Either ConfigError ()
forall a b. b -> Either a b
Right ()

-- | Require a CodeArtifact private read root for the mount format before checking its upstream chain.
vetPrivateRepository :: Ecosystem -> Target -> Either ConfigError ()
vetPrivateRepository :: Ecosystem -> Target -> Either ConfigError ()
vetPrivateRepository Ecosystem
eco Target
target = case Target -> StoreTag
tgtTag Target
target of
    -- The host is 'vetTargetTag''s to report, so a bad one is left to it rather than named twice.
    StoreTag
TagCodeArtifact | Either ConfigError (Text, Text, Text) -> Bool
forall a b. Either a b -> Bool
isRight (Ecosystem
-> Text -> RegistryUrl -> Either ConfigError (Text, Text, Text)
codeArtifactHost Ecosystem
eco Text
privateUpstreamKey (Target -> RegistryUrl
tgtUrl Target
target)) -> Either ConfigError (StoreBackend, CodeArtifactStore)
-> Either ConfigError ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Ecosystem
-> Target -> Either ConfigError (StoreBackend, CodeArtifactStore)
resolvePrivateBackend Ecosystem
eco Target
target)
    StoreTag
_ -> () -> Either ConfigError ()
forall a b. b -> Either a b
Right ()

-- | A CodeArtifact publication @uploadUrl@ addresses the same repository as its read root.
vetPublicationRepository :: Ecosystem -> PublicationEndpoint -> Either ConfigError ()
vetPublicationRepository :: Ecosystem -> PublicationEndpoint -> Either ConfigError ()
vetPublicationRepository Ecosystem
eco PublicationEndpoint
endpoint = case (Target -> StoreTag
tgtTag (PublicationEndpoint -> Target
peTarget PublicationEndpoint
endpoint), PublicationEndpoint -> Maybe RegistryUrl
peUploadUrl PublicationEndpoint
endpoint) of
    (StoreTag
TagCodeArtifact, Just RegistryUrl
upload) -> do
        original <- EndpointPurpose
-> Text -> RegistryUrl -> Either ConfigError CodeArtifactStore
store EndpointPurpose
RepositoryEndpoint Text
"publicationTarget.codeArtifact.url" (Target -> RegistryUrl
tgtUrl (PublicationEndpoint -> Target
peTarget PublicationEndpoint
endpoint))
        uploaded <- store UploadEndpoint "publicationTarget.codeArtifact.uploadUrl" upload
        unless (original == uploaded) (Left (ParseError "CodeArtifact publication uploadUrl must address the same read repository"))
    (StoreTag, Maybe RegistryUrl)
_ -> () -> Either ConfigError ()
forall a b. b -> Either a b
Right ()
  where
    store :: EndpointPurpose
-> Text -> RegistryUrl -> Either ConfigError CodeArtifactStore
store EndpointPurpose
purpose Text
key RegistryUrl
root = do
        (domain, owner, region) <- Ecosystem
-> Text -> RegistryUrl -> Either ConfigError (Text, Text, Text)
codeArtifactHost Ecosystem
eco Text
key RegistryUrl
root
        codeArtifactStore purpose eco key (registryUrlText root) domain owner region

privateUpstreamKey :: Text
privateUpstreamKey :: Text
privateUpstreamKey = Text
"privateUpstream.codeArtifact.url"

mirrorTargetKey :: Text
mirrorTargetKey :: Text
mirrorTargetKey = Text
"mirrorTarget.codeArtifact.url"

mintIdentity :: Text -> Text -> Text -> Maybe Natural -> CodeArtifactConfig
mintIdentity :: Text -> Text -> Text -> Maybe Natural -> CodeArtifactConfig
mintIdentity Text
domain Text
owner Text
region Maybe Natural
mDuration =
    CodeArtifactConfig
        { caRegion :: Text
caRegion = Text
region
        , caDomain :: Text
caDomain = Text
domain
        , caDomainOwner :: Maybe Text
caDomainOwner = Text -> Maybe Text
forall a. a -> Maybe a
Just Text
owner
        , caDurationSeconds :: Maybe Natural
caDurationSeconds = Maybe Natural
mDuration
        }

codeArtifactHost :: Ecosystem -> Text -> RegistryUrl -> Either ConfigError (Text, Text, Text)
codeArtifactHost :: Ecosystem
-> Text -> RegistryUrl -> Either ConfigError (Text, Text, Text)
codeArtifactHost Ecosystem
eco Text
key RegistryUrl
url =
    ConfigError
-> Maybe (Text, Text, Text)
-> Either ConfigError (Text, Text, Text)
forall l r. l -> Maybe r -> Either l r
maybeToRight
        (Ecosystem -> Text -> ConfigError
CodeArtifactHostMismatch Ecosystem
eco Text
key)
        (Text -> Maybe (Text, Text, Text)
parseCodeArtifactHost (Text -> Text
hostAddress (RegistryUrl -> Text
registryUrlText RegistryUrl
url)))

codeArtifactStore :: EndpointPurpose -> Ecosystem -> Text -> Text -> Text -> Text -> Text -> Either ConfigError CodeArtifactStore
codeArtifactStore :: EndpointPurpose
-> Ecosystem
-> Text
-> Text
-> Text
-> Text
-> Text
-> Either ConfigError CodeArtifactStore
codeArtifactStore EndpointPurpose
purpose Ecosystem
eco Text
key Text
raw Text
domain Text
owner Text
region = do
    format <- ConfigError
-> Maybe CodeArtifactFormat
-> Either ConfigError CodeArtifactFormat
forall l r. l -> Maybe r -> Either l r
maybeToRight (Ecosystem -> Text -> ConfigError
CodeArtifactFormatUnsupported Ecosystem
eco Text
key) (Ecosystem -> Maybe CodeArtifactFormat
codeArtifactFormat Ecosystem
eco)
    repository <- maybeToRight (repositoryError (formatToken format)) (repositoryOfPath purpose (formatToken format) raw)
    pure
        CodeArtifactStore
            { casDomain = domain
            , casDomainOwner = owner
            , casRegion = region
            , casRepository = repository
            , casFormat = format
            }
  where
    repositoryError :: Text -> ConfigError
repositoryError Text
format = case EndpointPurpose
purpose of
        EndpointPurpose
RepositoryEndpoint -> Ecosystem -> Text -> Text -> ConfigError
CodeArtifactRepositoryMissing Ecosystem
eco Text
key Text
format
        EndpointPurpose
UploadEndpoint ->
            Text -> ConfigError
ParseError
                ( Text
key
                    Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" must address /"
                    Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
format
                    Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"/{repository}/"
                    Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> if Text
format Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"pypi" then Text
" or /pypi/{repository}/legacy/" else Text
""
                )

repositoryOfPath :: EndpointPurpose -> Text -> Text -> Maybe Text
repositoryOfPath :: EndpointPurpose -> Text -> Text -> Maybe Text
repositoryOfPath EndpointPurpose
purpose Text
format Text
url = case (EndpointPurpose
purpose, Text -> [Text]
pathSegments Text
url) of
    (EndpointPurpose
_, [Text
pathFormat, Text
repository]) | Text
pathFormat Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
format -> Text -> Maybe Text
nonBlank Text
repository
    (EndpointPurpose
UploadEndpoint, [Text
"pypi", Text
repository, Text
"legacy"]) | Text
format Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"pypi" -> Text -> Maybe Text
nonBlank Text
repository
    (EndpointPurpose, [Text])
_ -> Maybe Text
forall a. Maybe a
Nothing

pathSegments :: Text -> [Text]
pathSegments :: Text -> [Text]
pathSegments = (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) ([Text] -> [Text]) -> (Text -> [Text]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"/" (Text -> [Text]) -> (Text -> Text) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
registryPath

-- | How a declared store asks for an ecosystem's service credential. Only CodeArtifact declares a mechanism.
storePresentation :: StoreTag -> Ecosystem -> ServicePresentation
storePresentation :: StoreTag -> Ecosystem -> ServicePresentation
storePresentation StoreTag
tag Ecosystem
eco = case StoreTag
tag of
    StoreTag
TagCodeArtifact -> (StoreOperation -> AuthMechanism) -> ServicePresentation
declaredPresentation (Ecosystem -> StoreOperation -> AuthMechanism
codeArtifactAuthMechanism Ecosystem
eco)
    StoreTag
TagRegistry -> ServicePresentation
nativePresentation
    StoreTag
TagVerdaccio -> ServicePresentation
nativePresentation

-- | Parse the CodeArtifact host into domain, owner and region, allowing hyphens in the domain.
parseCodeArtifactHost :: Text -> Maybe (Text, Text, Text)
parseCodeArtifactHost :: Text -> Maybe (Text, Text, Text)
parseCodeArtifactHost Text
host =
    case HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
".d.codeartifact." Text
host of
        [Text
domainOwner, Text
regionTail] -> do
            region <- Text -> Maybe Text
nonBlank (Text -> Maybe Text) -> Maybe Text -> Maybe Text
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Text -> Text -> Maybe Text
T.stripSuffix Text
".amazonaws.com" Text
regionTail
            let (domainDash, owner) = T.breakOnEnd "-" domainOwner
            domain <- nonBlank (T.dropEnd 1 domainDash)
            guard (isAccountId owner)
            pure (domain, owner, region)
        [Text]
_ -> Maybe (Text, Text, Text)
forall a. Maybe a
Nothing

-- | Recognise the 12-digit AWS account id shared by CodeArtifact and SQS URL parsing.
isAccountId :: Text -> Bool
isAccountId :: Text -> Bool
isAccountId Text
t = Text -> Int -> Ordering
T.compareLength Text
t Int
12 Ordering -> Ordering -> Bool
forall a. Eq a => a -> a -> Bool
== Ordering
EQ Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isDigit Text
t