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

{- | The sentences a reader sees for what the rules return. A rule returns facts, and a log line,
a denial body, or an audit line asks here for the text. Each render is total over its typed value,
so a reader needs no handler around it.
-}
module Ecluse.Core.Rules.Render (
    -- * A decision and its parts
    renderDecision,
    renderReason,
    renderInability,
    renderDuration,
) where

import Data.Scientific (FPFormat (Fixed), formatScientific, fromFloatDigits)
import Data.Text qualified as T
import Data.Time (NominalDiffTime, nominalDiffTimeToSeconds)

import Ecluse.Core.Package (renderPackageName, renderScope)
import Ecluse.Core.Rules.Types
import Ecluse.Core.Text.Iso8601 (renderIso8601Utc)
import Ecluse.Core.Version (renderVersion)

-- | A decision as one line, for logs and the denial response body.
renderDecision :: RuleEvidence -> Decision -> Text
renderDecision :: RuleEvidence -> Decision -> Text
renderDecision RuleEvidence
ev Decision
decision =
    let subject :: Text
subject = PackageName -> Text
renderPackageName (RuleEvidence -> PackageName
evName RuleEvidence
ev) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"@" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Version -> Text
renderVersion (RuleEvidence -> Version
evVersion RuleEvidence
ev)
     in case Decision
decision of
            Admitted Text
name Reason
reason [SkippedCheck]
skipped ->
                Text
subject Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" was approved by " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
name Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Reason -> Text
renderReason Reason
reason Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> [SkippedCheck] -> Text
renderSkippedChecks [SkippedCheck]
skipped
            Blocked Text
name Maybe DbEtag
_ Reason
reason ->
                Text
subject Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" was denied by " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
name Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Reason -> Text
renderReason Reason
reason
            BlockedByDefault [Reason]
reasons ->
                Text
subject
                    Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" was denied (no rule allowed it)"
                    Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> if [Reason] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Reason]
reasons
                        then Text
""
                        else Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
T.intercalate Text
"; " ((Reason -> Text) -> [Reason] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Reason -> Text
renderReason [Reason]
reasons)
            Undecidable Transience
_ Reason
reason ->
                Text
subject Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" could not be evaluated: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Reason -> Text
renderReason Reason
reason

-- The evidence as a parenthetical, so an admission's line never reads as if every check passed.
renderSkippedChecks :: [SkippedCheck] -> Text
renderSkippedChecks :: [SkippedCheck] -> Text
renderSkippedChecks [] = Text
""
renderSkippedChecks [SkippedCheck]
checks = Text
" (" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
T.intercalate Text
"; " ((SkippedCheck -> Text) -> [SkippedCheck] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map SkippedCheck -> Text
render [SkippedCheck]
checks) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"
  where
    render :: SkippedCheck -> Text
render = \case
        SkippedUnavailable Text
rule Inability
cause -> Text
"skipped for unavailability: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
rule Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" (" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Inability -> Text
renderInability Inability
cause Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"
        Unreached Text
rule -> Text
"not reached: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
rule

-- | One reason as the sentence the audit trail and a denial body carry.
renderReason :: Reason -> Text
renderReason :: Reason -> Text
renderReason = \case
    ScopeAllowListed Scope
scope -> Text
"scope " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Scope -> Text
renderScope Scope
scope Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" is allow-listed"
    ScopeNotAllowListed Scope
scope -> Text
"scope is not the allow-listed " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Scope -> Text
renderScope Scope
scope
    PublishedLongEnough NominalDiffTime
age NominalDiffTime
minAge ->
        Text
"published " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> NominalDiffTime -> Text
renderDuration NominalDiffTime
age Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" ago (at least " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> NominalDiffTime -> Text
renderDuration NominalDiffTime
minAge Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" old)"
    PublishedTooRecently NominalDiffTime
age NominalDiffTime
minAge ->
        Text
"published only " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> NominalDiffTime -> Text
renderDuration NominalDiffTime
age Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" ago, minimum age is " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> NominalDiffTime -> Text
renderDuration NominalDiffTime
minAge
    Reason
PublishTimeUnknown -> Text
"publish time is unknown"
    RunsOnInstall Text
how -> Text
"runs code on install: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
how
    Reason
NothingRunsOnInstall -> Text
"no install-time code execution"
    Reason
InstallCodeUndetermined -> Text
"install-time code execution not yet determined"
    FetchesOutside Text
which -> Text
"installs a dependency from outside the registry: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
which
    Reason
DependenciesThroughRegistry -> Text
"every installable dependency resolves through the registry"
    Reason
DependencySourcesUndetermined -> Text
"dependency sources not yet determined"
    Reason
VersionYanked -> Text
"version is yanked"
    Reason
VersionNotYanked -> Text
"version is not yanked"
    Reason
VersionDeprecated -> Text
"version is deprecated"
    Reason
VersionNotDeprecated -> Text
"version is not deprecated"
    IdentityRevoked Text
ident -> Text
"identity " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
ident Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" is revoked by operator"
    IdentityNotRevoked Text
ident -> Text
"identity is not the revoked " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
ident
    IdentityAllowListed Text
ident -> Text
"identity " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
ident Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" is allow-listed by operator"
    IdentityNotAllowListed Text
ident -> Text
"identity is not the allow-listed " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
ident
    Remediates AdvisoryIds
ids -> Text
"remediates " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed AdvisoryIds
ids
    RemediatesWithinLimits ScoreComparison
compared ->
        Text
"remediates " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed (ScoreComparison -> AdvisoryIds
scFixed ScoreComparison
compared) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" with " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed (ScoreComparison -> AdvisoryIds
scRemaining ScoreComparison
compared) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" remaining inside the limits" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ScoreComparison -> Text
renderComparison ScoreComparison
compared
    FixesButStillAffected AdvisoryIds
ids AdvisoryIds
open -> Text
"fixes " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed AdvisoryIds
ids Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" with " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed AdvisoryIds
open Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" remaining"
    RemediationBeyondLimits ScoreComparison
compared LimitShortfalls
shortfalls ->
        Text
"fixes "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed (ScoreComparison -> AdvisoryIds
scFixed ScoreComparison
compared)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" with "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed (ScoreComparison -> AdvisoryIds
scRemaining ScoreComparison
compared)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" remaining outside the limits: "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
T.intercalate Text
", " ((LimitShortfall -> Text) -> [LimitShortfall] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map LimitShortfall -> Text
renderShortfall (NonEmpty LimitShortfall -> [LimitShortfall]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (LimitShortfalls -> NonEmpty LimitShortfall
unLimitShortfalls LimitShortfalls
shortfalls)))
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ScoreComparison -> Text
renderComparison ScoreComparison
compared
    FixStillApplies AdvisoryIds
ids -> Text
"every advisory naming this version as its fix still applies to it: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed AdvisoryIds
ids
    Reason
FixesNoAdvisory -> Text
"no advisory names this version as its fix"
    AffectedBy AdvisoryScore
score Double
threshold AdvisoryIds
ids ->
        Text
"affected by " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed AdvisoryIds
ids Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" (" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" >= " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Double -> Text
forall b a. (Show a, IsString b) => a -> b
show Double
threshold Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"
    KnownMalicious AdvisoryIds
ids -> Text
"affected by " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed AdvisoryIds
ids Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" (known malicious)"
    Reason
NoKnownMaliciousAdvisory -> Text
"no known malicious advisory affects this version"
    NotAffectedAtThreshold AdvisoryScore
score ->
        Text
"no advisory at or above the " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" threshold affects this version"
    RuleUnable Text
rule Inability
inability -> Text
rule Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Inability -> Text
renderInability Inability
inability

-- | Why a rule could not vet, without the rule's name, which its holder prints beside it.
renderInability :: Inability -> Text
renderInability :: Inability -> Text
renderInability = \case
    Inability
PublishTimeUnread -> Text
"the publish time is not available"
    Inability
InstallSignalUnread -> Text
"the install-time execution signal is not available"
    Inability
AvailabilityUnread -> Text
"the availability flag is not available"
    Inability
DependencySourcesUnread -> Text
"the dependency sources are not available"
    Inability
NoDatabaseLoaded -> Text
"no advisory database loaded"
    -- The age, the maximum it passed, and when the push landed, so an operator can tell an
    -- update outage from a maximum set too short.
    PushPastMaximum AdvisoryAge
observed ->
        Text
"the advisory push is "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> NominalDiffTime -> Text
renderDuration (AdvisoryAge -> NominalDiffTime
advisoryAge AdvisoryAge
observed)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" old, past the maximum of "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> NominalDiffTime -> Text
renderDuration (AdvisoryAge -> NominalDiffTime
advisoryMaxAge AdvisoryAge
observed)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" (pushed at "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> UTCTime -> Text
renderIso8601Utc (AdvisoryAge -> UTCTime
advisoryPushedAt AdvisoryAge
observed)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"
    Inability
PushUndated -> Text
"the object store reported no publication time for the serving advisory artifact"
    Inability
SourceBreakerOpen -> Text
"the rule source circuit breaker is open"
    Inability
EvaluationFailed -> Text
"the rule could not be evaluated"
    RuleThrew Text
thrown -> Text
"the rule threw: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
thrown
    Inability
AttemptTimedOut -> Text
"the attempt timed out"

listed :: AdvisoryIds -> Text
listed :: AdvisoryIds -> Text
listed = Text -> [Text] -> Text
T.intercalate Text
", " ([Text] -> Text) -> (AdvisoryIds -> [Text]) -> AdvisoryIds -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NonEmpty Text -> [Text]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (NonEmpty Text -> [Text])
-> (AdvisoryIds -> NonEmpty Text) -> AdvisoryIds -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AdvisoryIds -> NonEmpty Text
unAdvisoryIds

renderComparison :: ScoreComparison -> Text
renderComparison :: ScoreComparison -> Text
renderComparison ScoreComparison
compared =
    Text
" (" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
T.intercalate Text
", " (AdvisoryScore -> Text -> ScoreSides -> Double -> ScoreGap -> [Text]
sideFacts AdvisoryScore
Cvss Text
"inclusive" (ScoreComparison -> ScoreSides
scCvss ScoreComparison
compared) (DifferentialLimits -> Double
dlMaxRemainingCvss DifferentialLimits
limits) (DifferentialLimits -> ScoreGap
dlCvssGap DifferentialLimits
limits) [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> AdvisoryScore -> Text -> ScoreSides -> Double -> ScoreGap -> [Text]
sideFacts AdvisoryScore
Epss Text
"exclusive" (ScoreComparison -> ScoreSides
scEpss ScoreComparison
compared) (DifferentialLimits -> Double
dlMaxRemainingEpss DifferentialLimits
limits) (DifferentialLimits -> ScoreGap
dlEpssGap DifferentialLimits
limits)) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"
  where
    limits :: DifferentialLimits
limits = ScoreComparison -> DifferentialLimits
scLimits ScoreComparison
compared
    sideFacts :: AdvisoryScore -> Text -> ScoreSides -> Double -> ScoreGap -> [Text]
sideFacts AdvisoryScore
score Text
bound ScoreSides
sides Double
limit ScoreGap
gap =
        [ Text
"remaining " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ScoreReading -> Text
renderReading (ScoreSides -> ScoreReading
ssHighestRemaining ScoreSides
sides)
        , AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" ceiling " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Double -> Text
renderScore Double
limit Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
bound
        , Text
"fixed " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ScoreReading -> Text
renderReading (ScoreSides -> ScoreReading
ssHighestFixed ScoreSides
sides)
        ]
            [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" gap at least " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Double -> Text
renderScore Double
least | GapOfAtLeast Double
least <- [ScoreGap
gap]]

renderShortfall :: LimitShortfall -> Text
renderShortfall :: LimitShortfall -> Text
renderShortfall = \case
    RemainingAboveCeiling AdvisoryScore
Cvss -> Text
"remaining CVSS above its ceiling"
    RemainingAboveCeiling AdvisoryScore
Epss -> Text
"remaining EPSS at or above its ceiling"
    RemainingUnscored AdvisoryScore
score AdvisoryIds
ids -> Text
"no " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" score for " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryIds -> Text
listed AdvisoryIds
ids
    FixedUnscored AdvisoryScore
score -> Text
"no fixed " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" score"
    GapBelowMinimum AdvisoryScore
score -> AdvisoryScore -> Text
scoreName AdvisoryScore
score Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" gap below its minimum"

renderReading :: ScoreReading -> Text
renderReading :: ScoreReading -> Text
renderReading = \case
    Scored Double
score -> Double -> Text
renderScore Double
score
    ScoreReading
Unscored -> Text
"unscored"

-- The shortest decimal that reads back as the stored score, never exponent notation.
renderScore :: Double -> Text
renderScore :: Double -> Text
renderScore Double
score
    | Double -> Bool
forall a. RealFloat a => a -> Bool
isNaN Double
score Bool -> Bool -> Bool
|| Double -> Bool
forall a. RealFloat a => a -> Bool
isInfinite Double
score = Double -> Text
forall b a. (Show a, IsString b) => a -> b
show Double
score
    | Bool
otherwise = String -> Text
forall a. ToText a => a -> Text
toText (FPFormat -> Maybe Int -> Scientific -> String
formatScientific FPFormat
Fixed Maybe Int
forall a. Maybe a
Nothing (Double -> Scientific
forall a. RealFloat a => a -> Scientific
fromFloatDigits Double
score))

scoreName :: AdvisoryScore -> Text
scoreName :: AdvisoryScore -> Text
scoreName = \case
    AdvisoryScore
Cvss -> Text
"CVSS"
    AdvisoryScore
Epss -> Text
"EPSS"

-- | Keep two non-zero units to distinguish near-threshold durations. Negative values render as zero.
renderDuration :: NominalDiffTime -> Text
renderDuration :: NominalDiffTime -> Text
renderDuration NominalDiffTime
d = case Int -> [(Text, Integer)] -> [(Text, Integer)]
forall a. Int -> [a] -> [a]
take Int
2 (Integer -> [(Text, Integer)]
durationComponents Integer
secs) of
    [] -> Text
"0 seconds"
    [(Text, Integer)]
parts -> [Text] -> Text
T.unwords (((Text, Integer) -> Text) -> [(Text, Integer)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Integer) -> Text
renderDurationPart [(Text, Integer)]
parts)
  where
    secs :: Integer
secs = Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
max Integer
0 (Pico -> Integer
forall b. Integral b => Pico -> b
forall a b. (RealFrac a, Integral b) => a -> b
round (NominalDiffTime -> Pico
nominalDiffTimeToSeconds NominalDiffTime
d)) :: Integer

durationLadder :: [(Text, Integer)]
durationLadder :: [(Text, Integer)]
durationLadder =
    [ (Text
"day", Integer
86400)
    , (Text
"hour", Integer
3600)
    , (Text
"minute", Integer
60)
    , (Text
"second", Integer
1)
    ]

durationComponents :: Integer -> [(Text, Integer)]
durationComponents :: Integer -> [(Text, Integer)]
durationComponents = [(Text, Integer)] -> Integer -> [(Text, Integer)]
forall {t} {a}. Integral t => [(a, t)] -> t -> [(a, t)]
go [(Text, Integer)]
durationLadder
  where
    go :: [(a, t)] -> t -> [(a, t)]
go [] t
_ = []
    go ((a
unit, t
size) : [(a, t)]
rest) t
r =
        let (t
q, t
r') = t
r t -> t -> (t, t)
forall a. Integral a => a -> a -> (a, a)
`divMod` t
size
         in [(a
unit, t
q) | t
q t -> t -> Bool
forall a. Ord a => a -> a -> Bool
> t
0] [(a, t)] -> [(a, t)] -> [(a, t)]
forall a. Semigroup a => a -> a -> a
<> [(a, t)] -> t -> [(a, t)]
go [(a, t)]
rest t
r'

-- Render one @(unit, count)@ component, pluralising the unit (@1 minute@, @30 seconds@).
renderDurationPart :: (Text, Integer) -> Text
renderDurationPart :: (Text, Integer) -> Text
renderDurationPart (Text
unit, Integer
n) = Integer -> Text
forall b a. (Show a, IsString b) => a -> b
show Integer
n Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
unit Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (if Integer
n Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
1 then Text
"" else Text
"s")