package eu.friedcutlet.yokan.app.profiles import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.services.files.exportFile import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.backup.SafetySnapshot import eu.friedcutlet.yokan.services.backup.BackupPlan import eu.friedcutlet.yokan.services.backup.BackupOpenResult import eu.friedcutlet.yokan.services.backup.RestoreMode import eu.friedcutlet.yokan.services.backup.BackupOptions import eu.friedcutlet.yokan.services.backup.BackupResult import eu.friedcutlet.yokan.services.backup.BackupSection import eu.friedcutlet.yokan.services.backup.RestorePreview internal data class TargetedBackupPlan(val target: ProfileId, val plan: BackupPlan) /** All stages carry the selected ID. Payload metadata never chooses or creates a destination. */ internal class ProfileBackupOperations(private val registry: ProfileRegistry, private val coordinator: ProfileCoordinator) { suspend fun export(id: ProfileId, options: BackupOptions, password: String?): BackupResult? = coordinator.withProfile(id) { owner -> val backup = owner.backup val exported = if (password.isNullOrEmpty()) backup.exportBackup(options) else backup.exportEncryptedBackup(options, password) val path = exportFile(exported.bytes, exported.fileName, exported.contentType, owner.database.settings().autoBackupLocation?.takeIf { it.isNotBlank() } ?: owner.localFiles.backupRoot) path?.let { registry.recordExport(id, it) BackupResult(exported.fileName, exported.bytes.size.toLong(), exported.itemCount, it) } } suspend fun open(id: ProfileId, bytes: ByteArray, password: String?): BackupOpenResult = coordinator.withProfile(id) { owner -> when (val opened = owner.backup.openBackup(bytes, password)) { is BackupOpenResult.Ready -> BackupOpenResult.Ready(profileRestorePlan(opened.plan, owner.database.settings())) is BackupOpenResult.Failure -> opened } } suspend fun read(id: ProfileId, path: String): ByteArray = coordinator.withProfile(id) { it.backup.readBackupFile(path) } suspend fun apply(target: TargetedBackupPlan, mode: RestoreMode): RestorePreview = coordinator.replaceProfileData(target.target) { owner -> // Re-read destination device fields after final progress has drained; never adopt imported grants. val plan = profileRestorePlan(target.plan, owner.database.settings()).withMode(mode) owner.backup.applyBackup(plan, mode) } suspend fun snapshots(id: ProfileId): List = coordinator.withProfile(id) { it.backup.listSafetySnapshots() } suspend fun rollback(id: ProfileId, snapshot: SafetySnapshot): RestorePreview = coordinator.replaceProfileData(id) { owner -> require(snapshot in owner.backup.listSafetySnapshots()) { "Safety snapshot belongs to another target or no longer exists" } owner.backup.rollbackSafetySnapshot(snapshot) } } /** Profile data can move; OS permissions, native paths and destination credentials stay with their owner. */ internal fun profileRestorePlan(plan: BackupPlan, current: DbSettings): BackupPlan { val incoming = plan.snapshot val settings = incoming.settings?.copy( cookiesList = current.cookiesList, sourcePreferences = current.sourcePreferences, downloadLocation = current.downloadLocation, autoBackupLocation = current.autoBackupLocation, localFolders = current.localFolders, namedLocalFolders = current.namedLocalFolders, downloadLocalFolderName = current.downloadLocalFolderName, jrePath = current.jrePath, extensionServerPath = current.extensionServerPath, androidProxyServer = current.androidProxyServer, themeSeedImagePath = current.themeSeedImagePath, lastTrackerLibraryLocation = current.lastTrackerLibraryLocation, desktopLaunchAtLogin = current.desktopLaunchAtLogin, backupEncryptionEnabled = current.backupEncryptionEnabled, backupEncryptionPassword = current.backupEncryptionPassword, metadataServerUrl = current.metadataServerUrl, metadataServerToken = current.metadataServerToken, features = current.features, btServerAddress = current.btServerAddress, btServerPort = current.btServerPort, ) val sections = plan.includedSections - BackupSection.TrackPreferences val snapshot = incoming.copy( settings = settings, includedSections = sections.toList(), trackPreferences = emptyList(), chapters = incoming.chapters.map { it.copy(archivePath = "", downloadSize = null) }, mangas = incoming.mangas.map { manga -> if (manga.isLocalArchive) manga.copy(link = null) else manga }, ) return BackupPlan( preview = plan.preview.copy(warnings = (plan.preview.warnings + "Device paths, local file links and login credentials are not imported. Downloaded files require relinking.").distinct()), snapshot = snapshot, includedSections = sections, resolvedPassword = null, mode = plan.mode, ) }