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

-- | Native facts of one index row, shared by projection and by retained mirror sources.
module Ecluse.Core.Registry.Cargo.SourceState (
    CargoRecordFacts (..),
    cargoRecordFacts,
    validateCargoSource,
    restrictCargoDocument,
    cargoSourceCompanions,
) where

import Data.Aeson (Value (..))
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (parseMaybe)
import Data.Set qualified as Set
import Data.Time (UTCTime)

import Ecluse.Core.Package (Artifact (..), Availability (Available, Yanked), HashAlg (SHA256), PackageDetails (..), mkHash)
import Ecluse.Core.Package.Entry (EntryKey, validRecordKey)
import Ecluse.Core.Registry (CompanionRequirement (DeclaredCompanions))
import Ecluse.Core.Registry.Cargo.Discovery (cargoArtifactCoordinate, coordinateFilename)
import Ecluse.Core.Registry.Cargo.Document (CargoDocument, cargoDocument, cargoRecords)
import Ecluse.Core.Registry.Cargo.Project (projectName)
import Ecluse.Core.Registry.Cargo.Wire (validateCargoRecord)
import Ecluse.Core.Registry.ServedDocument (stringField)
import Ecluse.Core.Registry.WireSupport (parsePublishTime)
import Ecluse.Core.Server.Path (unFilename)
import Ecluse.Core.Version (renderVersion)

-- | A schema-checked row's facts before any download binding. Text fields keep the published spelling.
data CargoRecordFacts = CargoRecordFacts
    { CargoRecordFacts -> Text
crfName :: Text
    , CargoRecordFacts -> Text
crfVersion :: Text
    , CargoRecordFacts -> Text
crfChecksum :: Text
    , CargoRecordFacts -> Maybe UTCTime
crfPublishedAt :: Maybe UTCTime
    -- ^ Absent or unparseable publication times stay unknown.
    , CargoRecordFacts -> Availability
crfAvailability :: Availability
    }
    deriving stock (CargoRecordFacts -> CargoRecordFacts -> Bool
(CargoRecordFacts -> CargoRecordFacts -> Bool)
-> (CargoRecordFacts -> CargoRecordFacts -> Bool)
-> Eq CargoRecordFacts
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CargoRecordFacts -> CargoRecordFacts -> Bool
== :: CargoRecordFacts -> CargoRecordFacts -> Bool
$c/= :: CargoRecordFacts -> CargoRecordFacts -> Bool
/= :: CargoRecordFacts -> CargoRecordFacts -> Bool
Eq, Int -> CargoRecordFacts -> ShowS
[CargoRecordFacts] -> ShowS
CargoRecordFacts -> String
(Int -> CargoRecordFacts -> ShowS)
-> (CargoRecordFacts -> String)
-> ([CargoRecordFacts] -> ShowS)
-> Show CargoRecordFacts
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CargoRecordFacts -> ShowS
showsPrec :: Int -> CargoRecordFacts -> ShowS
$cshow :: CargoRecordFacts -> String
show :: CargoRecordFacts -> String
$cshowList :: [CargoRecordFacts] -> ShowS
showList :: [CargoRecordFacts] -> ShowS
Show)

-- | Check the supported schema first, so the required fields below are present strings.
cargoRecordFacts :: Value -> Either Text CargoRecordFacts
cargoRecordFacts :: Value -> Either Text CargoRecordFacts
cargoRecordFacts Value
value = do
    Value -> Either Text ()
validateCargoRecord Value
value
    fields <- case Value
value of
        Object Object
objectFields -> Object -> Either Text Object
forall a b. b -> Either a b
Right Object
objectFields
        Value
_ -> Text -> Either Text Object
forall a b. a -> Either a b
Left Text
"invalid Cargo record"
    name <- maybeToRight "missing Cargo package name" (stringField "name" fields)
    version <- maybeToRight "missing Cargo version" (stringField "vers" fields)
    checksum <- maybeToRight "missing Cargo checksum" (stringField "cksum" fields)
    pure
        CargoRecordFacts
            { crfName = name
            , crfVersion = version
            , crfChecksum = checksum
            , crfPublishedAt = KeyMap.lookup "pubtime" fields >>= parseMaybe parsePublishTime
            , crfAvailability = if KeyMap.lookup "yanked" fields == Just (Bool True) then Yanked else Available
            }

-- | One retained row must reproduce its admitted archive identity and policy facts, or restoration refuses it.
validateCargoSource :: PackageDetails -> CargoDocument -> Either Text ()
validateCargoSource :: PackageDetails -> CargoDocument -> Either Text ()
validateCargoSource PackageDetails
details CargoDocument
document = case (CargoDocument -> [(EntryKey, Value)]
cargoRecords CargoDocument
document, NonEmpty Artifact -> [Artifact]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (PackageDetails -> NonEmpty Artifact
pkgArtifacts PackageDetails
details)) of
    ([(EntryKey
key, raw :: Value
raw@(Object Object
_))], [Artifact
artifact]) -> do
        facts <- Value -> Either Text CargoRecordFacts
cargoRecordFacts Value
raw
        unless (validRecordKey key && key == artEntryKey artifact) (Left "Cargo source coordinate disagrees with its artifact")
        unless (projectName (crfName facts) == Right (pkgName details) && crfVersion facts == renderVersion (pkgVersion details)) (Left "Cargo source identity disagrees with the admitted version")
        hash <- mkHash SHA256 (crfChecksum facts)
        coordinate <- cargoArtifactCoordinate (crfName facts) (pkgVersion details) hash
        unless (unFilename (coordinateFilename coordinate) == artFilename artifact && artHashes artifact == [hash]) (Left "Cargo source archive identity disagrees with its artifact")
        unless (crfPublishedAt facts == pkgPublishedAt details && crfAvailability facts == pkgAvailability details && isNothing (artCoreMetadata artifact) && isNothing (artSize artifact)) (Left "Cargo source policy facts disagree with the admitted version")
    ([(EntryKey, Value)], [Artifact])
_ -> Text -> Either Text ()
forall a b. a -> Either a b
Left Text
"Cargo requires exactly one paired source row and archive"

-- | Keep the admitted rows in native order without renumbering their physical coordinates.
restrictCargoDocument :: Set EntryKey -> CargoDocument -> CargoDocument
restrictCargoDocument :: Set EntryKey -> CargoDocument -> CargoDocument
restrictCargoDocument Set EntryKey
admitted = [(EntryKey, Value)] -> CargoDocument
cargoDocument ([(EntryKey, Value)] -> CargoDocument)
-> (CargoDocument -> [(EntryKey, Value)])
-> CargoDocument
-> CargoDocument
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((EntryKey, Value) -> Bool)
-> [(EntryKey, Value)] -> [(EntryKey, Value)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((EntryKey -> Set EntryKey -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set EntryKey
admitted) (EntryKey -> Bool)
-> ((EntryKey, Value) -> EntryKey) -> (EntryKey, Value) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (EntryKey, Value) -> EntryKey
forall a b. (a, b) -> a
fst) ([(EntryKey, Value)] -> [(EntryKey, Value)])
-> (CargoDocument -> [(EntryKey, Value)])
-> CargoDocument
-> [(EntryKey, Value)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CargoDocument -> [(EntryKey, Value)]
cargoRecords

-- | A retained crate needs a companion only where its artifact declares one, and index rows declare none.
cargoSourceCompanions :: CompanionRequirement
cargoSourceCompanions :: CompanionRequirement
cargoSourceCompanions = CompanionRequirement
DeclaredCompanions