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

-- | Managed index files restore each retained row unchanged.
module Ecluse.Core.Registry.Cargo.Mirror (
    cargoMirrorDocuments,
    cargoStateFormat,
) where

import Data.Aeson (object, (.:), (.=))

import Ecluse.Core.Mirror.Documents (MirrorDocuments (..))
import Ecluse.Core.Mirror.State (MirrorVersion, fragmentDetails, fragmentReadData, versionFragments)
import Ecluse.Core.Mirror.State.Codec (forceSourceEntries, parseSourceEntries, sourceEntries, sourceEntriesCharge)
import Ecluse.Core.Mirror.State.Format (MirrorStateFormat (..), noProjectEnvelope)
import Ecluse.Core.Mirror.State.Weight (fragmentShellAllowance, sourceEntriesWeight)
import Ecluse.Core.Package (Artifact (..), PackageDetails (pkgArtifacts))
import Ecluse.Core.Package.Entry (EntryKey (RecordEntry))
import Ecluse.Core.Registry.CachedDocument (cargoCached, cargoPacked)
import Ecluse.Core.Registry.Cargo.Document (cargoDocument, cargoRecords, packCargoDocument)
import Ecluse.Core.Registry.Cargo.Manifest (cratesIoIndex)
import Ecluse.Core.Registry.Cargo.SourceState (cargoSourceCompanions)
import Ecluse.Core.Registry.Metadata (VersionDoc (..))
import Ecluse.Core.Registry.MirrorUpload (MirrorReadData (CargoMirrorRead))
import Ecluse.Core.Server.Cache.VersionWeight.Fields (retainedRawWeight)

-- | Versions follow their original index positions, so a restored row keeps its original record coordinate until rebasing.
cargoMirrorDocuments :: MirrorDocuments
cargoMirrorDocuments :: MirrorDocuments
cargoMirrorDocuments =
    MirrorDocuments
        { mdRestore :: MirrorVersion -> [Artifact] -> Maybe VersionDoc
mdRestore = MirrorVersion -> [Artifact] -> Maybe VersionDoc
restoreCargoVersion
        , mdOrder :: [(Text, VersionDoc)] -> [(Text, VersionDoc)]
mdOrder = ((Text, VersionDoc) -> EntryKey)
-> [(Text, VersionDoc)] -> [(Text, VersionDoc)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn ((\(Artifact
artifact :| [Artifact]
_) -> Artifact -> EntryKey
artEntryKey Artifact
artifact) (NonEmpty Artifact -> EntryKey)
-> ((Text, VersionDoc) -> NonEmpty Artifact)
-> (Text, VersionDoc)
-> EntryKey
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PackageDetails -> NonEmpty Artifact
pkgArtifacts (PackageDetails -> NonEmpty Artifact)
-> ((Text, VersionDoc) -> PackageDetails)
-> (Text, VersionDoc)
-> NonEmpty Artifact
forall b c a. (b -> c) -> (a -> b) -> a -> c
. VersionDoc -> PackageDetails
vdDetails (VersionDoc -> PackageDetails)
-> ((Text, VersionDoc) -> VersionDoc)
-> (Text, VersionDoc)
-> PackageDetails
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text, VersionDoc) -> VersionDoc
forall a b. (a, b) -> b
snd)
        , mdEntryKey :: Int -> EntryKey
mdEntryKey = Int -> EntryKey
RecordEntry
        , mdRekey :: (EntryKey -> EntryKey) -> CachedDoc -> Maybe CachedDoc
mdRekey = \EntryKey -> EntryKey
rekey CachedDoc
raw -> do
            native <- (CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
-> CachedDoc -> Maybe CargoDocument
forall a b. (a, b) -> b
snd (CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
cargoCached CachedDoc
raw
            pure (fst cargoCached (cargoDocument [(rekey key, value) | (key, value) <- cargoRecords native]))
        , mdAssemble :: ProjectMirrorRecord -> [VersionDoc] -> CachedDoc
mdAssemble = \ProjectMirrorRecord
_ [VersionDoc]
docs -> (PackedIndex -> CachedDoc, CachedDoc -> Maybe PackedIndex)
-> PackedIndex -> CachedDoc
forall a b. (a, b) -> a
fst (PackedIndex -> CachedDoc, CachedDoc -> Maybe PackedIndex)
cargoPacked (CargoDocument -> PackedIndex
packCargoDocument ([(EntryKey, Value)] -> CargoDocument
cargoDocument ([[(EntryKey, Value)]] -> [(EntryKey, Value)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [CargoDocument -> [(EntryKey, Value)]
cargoRecords CargoDocument
document | VersionDoc
doc <- [VersionDoc]
docs, Just CachedDoc
raw <- [VersionDoc -> Maybe CachedDoc
vdRaw VersionDoc
doc], Just CargoDocument
document <- [(CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
-> CachedDoc -> Maybe CargoDocument
forall a b. (a, b) -> b
snd (CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
cargoCached CachedDoc
raw]])))
        }

-- | Each fragment keeps its original crates.io rows under their record coordinates. Their source identity grants no target authority.
cargoStateFormat :: MirrorStateFormat
cargoStateFormat :: MirrorStateFormat
cargoStateFormat =
    MirrorStateFormat
        { msfKind :: Text
msfKind = Text
"cargo"
        , msfEncodeSource :: MirrorReadData -> Maybe Value
msfEncodeSource = \case
            CargoMirrorRead CargoDocument
document -> Value -> Maybe Value
forall a. a -> Maybe a
Just ([Pair] -> Value
object [Key
"kind" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Text
"cargo" :: Text), Key
"sourceIndex" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Text
cratesIoIndex, Key
"entries" Key -> [Value] -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [(EntryKey, Value)] -> [Value]
sourceEntries (CargoDocument -> [(EntryKey, Value)]
cargoRecords CargoDocument
document)])
            MirrorReadData
_ -> Maybe Value
forall a. Maybe a
Nothing
        , msfDecodeSource :: Object -> Parser MirrorReadData
msfDecodeSource = \Object
value -> do
            sourceIndex <- Object
value Object -> Key -> Parser Text
forall a. FromJSON a => Object -> Key -> Parser a
.: Key
"sourceIndex"
            unless (sourceIndex == cratesIoIndex) (fail "Cargo mirror source is not crates.io")
            CargoMirrorRead . cargoDocument <$> parseSourceEntries "Cargo entry" value
        , msfDecodeCharge :: Value -> Integer
msfDecodeCharge = Value -> Integer
sourceEntriesCharge
        , msfForceSource :: MirrorReadData -> ()
msfForceSource = \case
            CargoMirrorRead CargoDocument
document -> [(EntryKey, Value)] -> ()
forceSourceEntries (CargoDocument -> [(EntryKey, Value)]
cargoRecords CargoDocument
document)
            MirrorReadData
_ -> ()
        , msfEnvelope :: ProjectEnvelope
msfEnvelope = Text -> ProjectEnvelope
noProjectEnvelope Text
"Cargo"
        , msfFragmentShell :: PackageDetails -> Integer
msfFragmentShell = Integer -> PackageDetails -> Integer
forall a b. a -> b -> a
const Integer
fragmentShellAllowance
        , msfSourceWeight :: MirrorReadData -> Integer
msfSourceWeight = \case
            CargoMirrorRead CargoDocument
document -> CachedDoc -> Integer
retainedRawWeight ((CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
-> CargoDocument -> CachedDoc
forall a b. (a, b) -> a
fst (CargoDocument -> CachedDoc, CachedDoc -> Maybe CargoDocument)
cargoCached CargoDocument
document) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ [(EntryKey, Value)] -> Integer
sourceEntriesWeight (CargoDocument -> [(EntryKey, Value)]
cargoRecords CargoDocument
document)
            MirrorReadData
_ -> Integer
0
        , msfCompanions :: CompanionRequirement
msfCompanions = CompanionRequirement
cargoSourceCompanions
        }

restoreCargoVersion :: MirrorVersion -> [Artifact] -> Maybe VersionDoc
restoreCargoVersion :: MirrorVersion -> [Artifact] -> Maybe VersionDoc
restoreCargoVersion MirrorVersion
mirror [Artifact]
current = do
    fragment :| [] <- NonEmpty StoredMirrorFragment
-> Maybe (NonEmpty StoredMirrorFragment)
forall a. a -> Maybe a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorVersion -> NonEmpty StoredMirrorFragment
versionFragments MirrorVersion
mirror)
    CargoMirrorRead source <- pure (fragmentReadData fragment)
    artifact :| [] <- pure (pkgArtifacts (fragmentDetails fragment))
    [(key, _)] <- pure (cargoRecords source)
    native <- find ((== artFilename artifact) . artFilename) current
    guard (key == artEntryKey artifact)
    pure (VersionDoc (fragmentDetails fragment){pkgArtifacts = artifact{artUrl = artUrl native} :| []} (Just (fst cargoCached source)))