// 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, !shoeGaze.boards.isEmpty else { return } let entry: RigEntry = shoeGaze.captureEntry(name: seedName) do { try store.save(entry) // The seeded entry was captured from the working graph, so it is the session's source // rig — record it so the sidebar highlights it and the autosave envelope carries it. shoeGaze.currentRigID = entry.id } catch { print("[RigLibraryBootstrap] seeding library failed: \(error)") } } }