// processor_state.cpp — ReaSamplerProcessor's component-state I/O (setState/getState
// against the component_state_io codec) and its UI-thread parameter accessors/setters
// (selection, the one parameter set, channel mode, preview velocity, voice-system params,
// master gain, preview-note mailbox posts). Everything here runs off the audio thread;
// setters hand work to the reload family (processor_reload.cpp) or store atomics
// process() picks up at block start.

#include "shell/instrument/reasampler_processor.h"

#include <cstdint>
#include <mutex>
#include <vector>

#include "pluginterfaces/base/ibstream.h"

#include "core/instrument/engine/master_gain.h"      // masterGainMaxLinear (post-mixer gain clamp)
#include "core/instrument/map/component_state_io.h"  // the ComponentState codec
#include "core/instrument/map/sample_map.h"          // retainRefs / referencedSampleIds

using namespace Steinberg;
using namespace Steinberg::Vst;

namespace reasampler::vst {

using namespace instrument::map;  // the codec + resolution vocabulary this TU marshals
using instrument::engine::masterGainMaxLinear;  // taper ceiling

tresult PLUGIN_API ReaSamplerProcessor::setState(IBStream* state) {
    if (!state) return kResultFalse;
    // The blob is small; read it in one shot into a growable buffer.
    std::vector<std::uint8_t> bytes;
    std::uint8_t chunk[256];
    int32 got = 0;
    while (state->read(chunk, sizeof(chunk), &got) == kResultOk && got > 0) {
        bytes.insert(bytes.end(), chunk, chunk + got);
    }
    // Component state is {loaded capture id, one parameter set}. deserializeComponentState
    // lifts older blobs cleanly — including the retired zone payloads, which adopt zone
    // one's capture into cs.selectionId. sampleRate_ is the real host rate here (REAPER
    // calls setupProcessing before setState on load), which the legacy v3 payload's
    // frames->seconds conversion needs.
    const ComponentState cs = deserializeComponentState(bytes, sampleRate_);
    setSelectedSampleId(cs.selectionId);
    setInstrumentParams(cs.params);
    // Restore the last-consumed assignment generation so a re-open does not re-apply a
    // stale assign_request.
    {
        std::lock_guard<std::mutex> lock(assignMarkerMutex_);
        lastConsumedAssignGeneration_ = cs.lastConsumedAssignGeneration;
    }
    // The output bus is fixed stereo (see initialize) — the mode only governs decode below.
    {
        std::lock_guard<std::mutex> lock(channelModeMutex_);
        channelMode_ = cs.channelMode;
        channelModeExplicit_ = cs.channelModeExplicit;
    }
    {
        std::lock_guard<std::mutex> lock(previewMutex_);
        previewVelocity_ = cs.previewVelocity;
    }
    // Restore before the reload so the rebuilt engine is born with the saved polyphony/mode.
    {
        std::lock_guard<std::mutex> lock(voiceParamsMutex_);
        voiceCount_ = cs.voiceCount;
        voiceMode_ = cs.voiceMode;
        monoTrigger_ = cs.monoTrigger;
    }
    setMasterGainLinear(cs.masterGainLinear);
    // Restore the instance-owned sample refs before the reload so it decodes straight from
    // them — no bank read required. A pre-v10 blob lifts to an empty table; the reload
    // resolves nothing until the bank blob becomes readable (opportunistic refresh, or
    // pollBankSync's legacy lift), after which the next save is self-contained.
    {
        std::lock_guard<std::mutex> lock(refsMutex_);
        sampleRefs_ = cs.sampleRefs;
    }
    // Restore the publish identity (pre-v11 lifts to empty, minted on first publish).
    // usageNonce_ resets: a restored blob is a new lifetime, so this incarnation can never
    // be mistaken for the previous one's writes or a copy-sibling's.
    {
        std::lock_guard<std::mutex> lock(usageMutex_);
        instanceGuid_ = cs.instanceGuid;
        usageNonce_.clear();
    }
    // A new blob is new facts — the legacy lift gets one fresh run per restored state.
    legacyLiftConcluded_.store(false, std::memory_order_relaxed);
    reloadInstrument();
    return kResultOk;
}

tresult PLUGIN_API ReaSamplerProcessor::getState(IBStream* state) {
    if (!state) return kResultFalse;
    // Persists the full instance state — never written to the "reasampler" bank ext-state.
    // No pick serializes to {"", default params}, restoring as silence (never auto-playing
    // sample #1).
    ComponentState state_out;
    state_out.selectionId = selectedSampleId();
    state_out.params = instrumentParams();
    {
        std::lock_guard<std::mutex> lock(channelModeMutex_);
        state_out.channelMode = channelMode_;
        state_out.channelModeExplicit = channelModeExplicit_;
    }
    {
        std::lock_guard<std::mutex> lock(assignMarkerMutex_);
        state_out.lastConsumedAssignGeneration = lastConsumedAssignGeneration_;
    }
    state_out.previewVelocity = previewVelocity();
    {
        std::lock_guard<std::mutex> lock(voiceParamsMutex_);
        state_out.voiceCount = voiceCount_;
        state_out.voiceMode = voiceMode_;
        state_out.monoTrigger = monoTrigger_;
    }
    state_out.masterGainLinear = masterGainLinear();
    // Persist the owned sample refs — the saved blob decodes + plays with no extension
    // present. Filtered (snapshot copy only) to what the instance currently plays, so the
    // table cannot grow with browsing history.
    state_out.sampleRefs = sampleRefs();
    retainRefs(state_out.sampleRefs, referencedSampleIds(state_out.selectionId));
    // Persist the publish identity so the usage key is stable across sessions.
    {
        std::lock_guard<std::mutex> lock(usageMutex_);
        state_out.instanceGuid = instanceGuid_;
    }
    const std::vector<std::uint8_t> bytes = serializeComponentState(state_out);
    if (!bytes.empty()) {
        const tresult wr = state->write(const_cast<std::uint8_t*>(bytes.data()),
                                        static_cast<int32>(bytes.size()), nullptr);
        if (wr != kResultOk) return wr;
    }
    return kResultOk;
}

std::string ReaSamplerProcessor::selectedSampleId() {
    std::lock_guard<std::mutex> lock(selectionMutex_);
    return selectedSampleId_;
}

void ReaSamplerProcessor::setSelectedSampleId(const std::string& id) {
    std::lock_guard<std::mutex> lock(selectionMutex_);
    selectedSampleId_ = id;
}

InstrumentParams ReaSamplerProcessor::instrumentParams() {
    std::lock_guard<std::mutex> lock(paramsMutex_);
    return params_;
}

void ReaSamplerProcessor::setInstrumentParams(const InstrumentParams& params) {
    std::lock_guard<std::mutex> lock(paramsMutex_);
    params_ = params;
}

SampleRefs ReaSamplerProcessor::sampleRefs() {
    std::lock_guard<std::mutex> lock(refsMutex_);
    return sampleRefs_;
}

ChannelMode ReaSamplerProcessor::channelMode() {
    std::lock_guard<std::mutex> lock(channelModeMutex_);
    return channelMode_;
}

std::uint8_t ReaSamplerProcessor::previewVelocity() {
    std::lock_guard<std::mutex> lock(previewMutex_);
    return previewVelocity_;
}

void ReaSamplerProcessor::setPreviewVelocity(std::uint8_t velocity) {
    // Clamp to [1,127] — 0 would be a note-off by convention, and a preview strike must sound.
    if (velocity < 1) velocity = 1;
    if (velocity > 127) velocity = 127;
    std::lock_guard<std::mutex> lock(previewMutex_);
    previewVelocity_ = velocity;
}

int ReaSamplerProcessor::voiceCount() {
    std::lock_guard<std::mutex> lock(voiceParamsMutex_);
    return voiceCount_;
}

void ReaSamplerProcessor::setVoiceCount(int count) {
    // Clamp to the shared pure-core range so the engine, state bytes, and editor control
    // can never disagree about the legal polyphony span.
    if (count < kMinVoiceCount) count = kMinVoiceCount;
    if (count > kMaxVoiceCount) count = kMaxVoiceCount;
    {
        std::lock_guard<std::mutex> lock(voiceParamsMutex_);
        if (voiceCount_ == count) return;  // no-op: don't churn a rebuild
        voiceCount_ = count;
    }
    // Light rebuild through the drain-slot swap (no bridge re-read, no WAV re-decode) so a
    // voice-param change never cuts a sounding tail. Same contract below.
    rebuildVoiceEngine();
}

VoiceMode ReaSamplerProcessor::voiceMode() {
    std::lock_guard<std::mutex> lock(voiceParamsMutex_);
    return voiceMode_;
}

void ReaSamplerProcessor::setVoiceMode(VoiceMode mode) {
    {
        std::lock_guard<std::mutex> lock(voiceParamsMutex_);
        if (voiceMode_ == mode) return;
        voiceMode_ = mode;
    }
    rebuildVoiceEngine();
}

MonoTrigger ReaSamplerProcessor::monoTrigger() {
    std::lock_guard<std::mutex> lock(voiceParamsMutex_);
    return monoTrigger_;
}

void ReaSamplerProcessor::setMonoTrigger(MonoTrigger trigger) {
    {
        std::lock_guard<std::mutex> lock(voiceParamsMutex_);
        if (monoTrigger_ == trigger) return;
        monoTrigger_ = trigger;
    }
    rebuildVoiceEngine();
}

void ReaSamplerProcessor::setMasterGainLinear(double linear) {
    // Clamp to the master_gain taper (0 = silence, cap = +24 dB). One relaxed atomic
    // store — no rebuild, no lock (a post-sum trim is not a keymap fact).
    if (!(linear >= 0.0)) linear = 0.0;  // also catches NaN
    const double maxLin = masterGainMaxLinear();
    if (linear > maxLin) linear = maxLin;
    masterGain_.store(static_cast<float>(linear), std::memory_order_relaxed);
}

void ReaSamplerProcessor::previewNoteOn(int note) {
    if (note < 0) note = 0;
    if (note > 127) note = 127;
    const std::uint8_t vel = previewVelocity();  // latch the current knob value into the request
    // Advance the sequence (wrapping; process compares for inequality — 16 bits gives 65535
    // posts between collisions, unreachable at UI-click rates).
    const std::uint16_t seq = ++previewOnSeq_ == 0 ? ++previewOnSeq_ : previewOnSeq_;
    const std::uint32_t packed = (static_cast<std::uint32_t>(seq) << 16) |
                                 (static_cast<std::uint32_t>(vel) << 8) |
                                 static_cast<std::uint32_t>(note & 0xFF);
    previewOnRequest_.store(packed, std::memory_order_release);
}

void ReaSamplerProcessor::previewNoteOff(int note) {
    if (note < 0) note = 0;
    if (note > 127) note = 127;
    const std::uint16_t seq = ++previewOffSeq_ == 0 ? ++previewOffSeq_ : previewOffSeq_;
    const std::uint32_t packed = (static_cast<std::uint32_t>(seq) << 16) |
                                 static_cast<std::uint32_t>(note & 0xFF);
    previewOffRequest_.store(packed, std::memory_order_release);
}

void ReaSamplerProcessor::setChannelMode(ChannelMode mode) {
    {
        std::lock_guard<std::mutex> lock(channelModeMutex_);
        // A deliberate choice either way: latch explicit even on a same-mode click so
        // auto-default stops fighting it.
        channelModeExplicit_ = true;
        if (channelMode_ == mode) return;  // no decode change: don't churn a reload
        channelMode_ = mode;
    }
    // The output bus is fixed stereo (no bus repoint): reloading re-decodes off-thread
    // under the new mode and the RT path just keeps rendering.
    reloadInstrument();
}

}  // namespace reasampler::vst
