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

-- | PyPI name normalisation, reached through 'Ecluse.Core.Package.canonicalise'.
module Ecluse.Core.Package.Pep503 (
    normalisePyPI,
) where

import Data.Text qualified as T

import Ecluse.Core.Text (toLowerUnlessAsciiUnchanged)

-- | Lowercase and collapse @-_.@ runs for PyPI keys, dropping edge separators without validating names.
normalisePyPI :: Text -> Text
normalisePyPI :: Text -> Text
normalisePyPI Text
t
    | Text -> Bool
hasCanonicalSeparators Text
lowered = Text
lowered
    | Bool
otherwise =
        Text -> [Text] -> Text
T.intercalate Text
"-"
            ([Text] -> Text) -> (Text -> [Text]) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (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
forall a b. (a -> b) -> a -> b
$ (Char -> Char) -> Text -> Text
T.map (\Char
c -> if Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.' then Char
'-' else Char
c) Text
lowered
  where
    lowered :: Text
lowered = Text -> Text
toLowerUnlessAsciiUnchanged Text
t

hasCanonicalSeparators :: Text -> Bool
hasCanonicalSeparators :: Text -> Bool
hasCanonicalSeparators Text
t =
    Bool -> Bool
not ((Char -> Bool) -> Text -> Bool
T.any (\Char
c -> Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.') Text
t)
        Bool -> Bool -> Bool
&& Bool -> Bool
not (Text -> Text -> Bool
T.isPrefixOf Text
"-" Text
t)
        Bool -> Bool -> Bool
&& Bool -> Bool
not (Text -> Text -> Bool
T.isSuffixOf Text
"-" Text
t)
        Bool -> Bool -> Bool
&& Bool -> Bool
not (Text -> Text -> Bool
T.isInfixOf Text
"--" Text
t)