// RigLibraryBootstrap.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import LyrebirdShoeGaze /// Setup of the rig library for an app shell, split so nothing blocks the launch path. /// /// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous /// initializer and hand to the UI). ``start(_:seedFrom:)`` then does the blocking work — resolving /// the iCloud-or-local location and the initial load — off the main thread, then performs a one-time /// catch-up seed of any missing shipped starter rigs. @MainActor public enum RigLibraryBootstrap { /// `UserDefaults` key holding the highest ``FactoryRigLibrary/seedVersion`` this device has /// already seeded. Per-device (not synced): the seed is idempotent by stable rig id, so a device /// that receives the rigs via iCloud sync simply finds them already present and seeds nothing. private static let seedVersionKey: String = "net.realizedsound.shoegaze.factorySeedVersion" /// Creates an auto-resolving store. Construct this synchronously at launch; call /// ``start(_:seedFrom:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`). public static func makeStore() -> RigLibraryStore { RigLibraryStore() } /// Resolves + loads `store` off the main thread, then performs a one-time catch-up seed of any /// missing shipped starter rigs. Idempotent — safe to call once at every launch. /// /// Seeding adds only factory rigs whose stable ids are **not already present**, so it never /// duplicates a rig and never touches the user's own rigs. It runs at most once per /// ``FactoryRigLibrary/seedVersion``: a first launch seeds every starter; a launch after an /// update that ships new starters seeds just the new ones; and a starter the user later deletes /// stays deleted (the version marker has already advanced). This deliberately replaces the old /// "only seed an empty library" rule so users who already had rigs still receive the starters. /// /// - Parameters: /// - store: The store from ``makeStore()``. /// - shoeGaze: The working session (currently unused by seeding; kept for call-site stability /// and future working-rig seeding needs). public static func start( _ store: RigLibraryStore, seedFrom shoeGaze: ShoeGaze ) async { await store.start() let defaults: UserDefaults = .standard let seededVersion: Int = defaults.integer(forKey: seedVersionKey) // 0 when never seeded guard seededVersion < FactoryRigLibrary.seedVersion else { return } // Seed missing starters. Only advance the marker if seeding succeeded, so a transient failure // (which should not happen for this deterministic data) is retried on the next launch. if seedMissingFactoryRigs(into: store) { defaults.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey) } } /// Adds any shipped starter rig not already in `store`, keyed by stable id. Safe to call anytime. /// /// Use this to drive a user-facing "Restore Starter Rigs" action: it re-adds starters the user /// deleted (and any newly-shipped ones) without disturbing their own rigs, and advances the seed /// marker so automatic catch-up seeding won't fight the manual restore. /// /// - Parameter store: The library to seed into. /// - Returns: The number of starter rigs added (0 if all were already present). @discardableResult public static func restoreStarterRigs(into store: RigLibraryStore) -> Int { let added: Int = addMissingFactoryRigs(into: store) UserDefaults.standard.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey) return added } /// Seeds missing starters, returning whether the operation completed without a build/encode error /// (so the caller knows whether to advance the seed marker). private static func seedMissingFactoryRigs(into store: RigLibraryStore) -> Bool { do { _ = try addMissingFactoryRigsThrowing(into: store) return true } catch { print("[RigLibraryBootstrap] seeding factory rigs failed: \(error)") return false } } /// Non-throwing convenience: seeds missing starters and returns the count added (0 on error). private static func addMissingFactoryRigs(into store: RigLibraryStore) -> Int { do { return try addMissingFactoryRigsThrowing(into: store) } catch { print("[RigLibraryBootstrap] restoring factory rigs failed: \(error)") return 0 } } /// Builds the starter rigs and saves the ones whose ids are missing from `store`. /// /// - Returns: The number of rigs added. /// - Throws: Any error from building the rigs or a synchronous encode failure in `store.save`. private static func addMissingFactoryRigsThrowing(into store: RigLibraryStore) throws -> Int { let existingIDs: Set = Set(store.entries.map { $0.id }) let missing: [RigEntry] = try FactoryRigLibrary.makeEntries().filter { !existingIDs.contains($0.id) } for entry: RigEntry in missing { try store.save(entry) } return missing.count } }