// 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:seedName:)`` then does the blocking work — /// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the /// library from the current working rig **only after** the real (possibly iCloud) contents are /// known, so a first launch can't create a duplicate "Default" rig on every synced device. @MainActor public enum RigLibraryBootstrap { /// Creates an auto-resolving store. Construct this synchronously at launch; call /// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`). public static func makeStore() -> RigLibraryStore { RigLibraryStore() } /// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still /// empty after loading (first run). Idempotent enough to call once at launch. /// /// - Parameters: /// - store: The store from ``makeStore()``. /// - shoeGaze: The session whose current rig seeds the library when it is first empty. /// - seedName: Name for the seeded first rig. Defaults to `"Default"`. public static func start( _ store: RigLibraryStore, seedFrom shoeGaze: ShoeGaze, seedName: String = "Default" ) async { await store.start() // Seed only after the (possibly iCloud) library has loaded: an empty library here means a // genuine first run, not a not-yet-synced one. guard store.entries.isEmpty else { return } // First run: populate the library with the shipped starter rigs. These are built in // throwaway offline sessions, so they are independent of the current working graph. The // working session is intentionally left as-is (no `currentRigID`) — the user picks a starter // rig from the sidebar to load it, rather than the highlight pointing at a rig the working // graph has not actually loaded. let entries: [RigEntry] do { entries = try FactoryRigLibrary.makeEntries() } catch { // Building the shipped rigs is deterministic and should never fail at runtime; if it // somehow does, fall back to seeding the working rig so the library is not left empty. print("[RigLibraryBootstrap] building factory rigs failed: \(error)") seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName) return } // Save sequentially, rolling back on failure. Seeding is gated on `store.entries.isEmpty`, // so a partially-saved library would be frozen forever (never retried, never completed). If // any save fails, delete the entries saved this run so the library returns to empty and a // later launch retries the full seed. (This is best-effort, not truly atomic: if a rollback // `delete` itself fails, a partial set can still be left behind and frozen — the residual // hole a non-transactional store cannot fully close.) var savedThisRun: [RigEntry] = [] do { for entry: RigEntry in entries { try store.save(entry) savedThisRun.append(entry) } } catch { print("[RigLibraryBootstrap] seeding factory rigs failed after " + "\(savedThisRun.count)/\(entries.count); rolling back: \(error)") for entry: RigEntry in savedThisRun { do { try store.delete(entry) } catch { print("[RigLibraryBootstrap] rollback of '\(entry.name)' failed: \(error)") } } } } /// Seeds the working session's current rig as a single named library entry. /// /// Last-resort fallback used only when the factory rigs could not be built; keeps the library /// from being left empty on first run. private static func seedWorkingRig( _ store: RigLibraryStore, seedFrom shoeGaze: ShoeGaze, seedName: String ) { guard !shoeGaze.boards.isEmpty else { return } let entry: RigEntry = shoeGaze.captureEntry(name: seedName) do { try store.save(entry) shoeGaze.currentRigID = entry.id } catch { print("[RigLibraryBootstrap] fallback seeding failed: \(error)") } } }