// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later

package space.rcmd.android.sizzle.io

import space.rcmd.android.sizzle.model.Project
import java.io.File

/**
 * Autosaves the whole [Project] to a single file in the app's scoped storage and
 * restores it on the next launch — this is the crash-recovery / resume-where-you-
 * left-off layer. The payload is the full-fidelity [ProjectIo] text, so every
 * musical, mixer and toolbox parameter is preserved.
 *
 * Note: the Sampler's actual audio lives in the in-memory SampleStore, not in the
 * project text; pad assignments and params are restored, but re-import a sample
 * (or load a saved preset) to hear it again after a cold restart.
 */
class ProjectStore(private val file: File) {

    /** Write the current project. Never throws — a failed autosave must not crash. */
    fun save(project: Project) {
        runCatching {
            file.parentFile?.mkdirs()
            file.writeText(ProjectIo.save(project))
        }
    }

    /** Restore the autosaved project into [project] in place. Returns true on
     *  success; a missing or corrupt file leaves [project] untouched. */
    fun restore(project: Project): Boolean =
        runCatching {
            if (!file.exists()) return false
            ProjectIo.loadInto(project, file.readText())
            true
        }.getOrDefault(false)
}
