// RigLibraryBootstrap.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import LyrebirdShoeGaze /// One-call setup of the rig library for an app shell. /// /// Resolves the (iCloud-or-local) library location, constructs and starts a ``RigLibraryStore``, /// seeds it with the current working rig the first time it is empty (so the listing is never blank /// and the user's existing setup becomes their first saved rig), and reports which entry should be /// highlighted as the current rig on this launch. @MainActor public enum RigLibraryBootstrap { /// The result of bootstrapping: a started store and the rig to highlight at launch. public struct Result { public let store: RigLibraryStore public let initialRigID: UUID? } /// Builds and starts the rig library for `shoeGaze`. /// /// - Important: Resolving the iCloud container performs blocking I/O. Call this once at app /// startup; it is acceptable there but should not be called repeatedly. /// /// - Parameters: /// - shoeGaze: The session whose current rig seeds the library when it is first empty. /// - seedName: Name for the seeded first rig. Defaults to `"Default"`. /// - Returns: The started store and the entry id to seed the builder's current-rig highlight. public static func make( for shoeGaze: ShoeGaze, seedName: String = "Default" ) -> Result { let resolved: RigLibraryLocation.Resolved = RigLibraryLocation.resolve() let store: RigLibraryStore = RigLibraryStore(resolved: resolved) store.start() let defaults: UserDefaults = UserDefaults.standard let key: String = ShoeGazeBuilderView.currentRigDefaultsKey // First run with an empty library: capture the current working rig as the first entry and // remember it as current. if store.entries.isEmpty, !shoeGaze.boards.isEmpty { let entry: RigEntry = shoeGaze.captureEntry(name: seedName) do { try store.save(entry) defaults.set(entry.id.uuidString, forKey: key) } catch { print("[RigLibraryBootstrap] seeding library failed: \(error)") } } // Resolve the highlight only if the remembered id still exists in the library. let initial: UUID? = { guard let stored: String = defaults.string(forKey: key), let id: UUID = UUID(uuidString: stored), store.entries.contains(where: { $0.id == id }) else { return nil } return id }() return Result(store: store, initialRigID: initial) } }