#include "gui/SpectrumPreviewLogic.h"

#include <array>
#include <cmath>
#include <cstdio>
#include <limits>

namespace {

int fail(const char* message)
{
    std::fprintf(stderr, "spectrum_preview_logic_test: %s\n", message);
    return 1;
}

bool nearlyEqual(double a, double b, double epsilon = 1.0e-12)
{
    return std::abs(a - b) <= epsilon;
}

int testCursorAnchoredZoom()
{
    using namespace AetherSDR;
    const FrequencyFrame base{14.1, 0.2};
    constexpr std::array<double, 5> kFractions{
        -0.5, -0.25, 0.0, 0.31, 0.5,
    };
    constexpr std::array<double, 2> kBandwidths{0.08, 0.45};
    for (double fraction : kFractions) {
        const double anchorMhz = frequencyAtFraction(base, fraction);
        for (double bandwidthMhz : kBandwidths) {
            const double centerMhz = centerForAnchoredBandwidth(
                anchorMhz, fraction, bandwidthMhz);
            const FrequencyFrame zoomed{centerMhz, bandwidthMhz};
            if (!nearlyEqual(frequencyAtFraction(zoomed, fraction),
                             anchorMhz)) {
                return fail("cursor anchor moved during zoom");
            }
        }
    }
    if (!nearlyEqual(frequencyCanvasFraction(250.0, 1000), -0.25)
        || !nearlyEqual(frequencyCanvasFraction(-100.0, 1000), -0.5)
        || !nearlyEqual(frequencyCanvasFraction(1200.0, 1000), 0.5)) {
        return fail("frequency canvas fraction should clamp to the canvas");
    }
    return 0;
}

int testFrequencyFrameMapping()
{
    using namespace AetherSDR;
    const FrequencyFrame source{14.0, 0.2};
    const FrequencyFrame pannedTarget{14.05, 0.2};
    const FrequencyFrame zoomedTarget{14.0, 0.1};
    if (!nearlyEqual(sourceUnitPosition(0.5, source, pannedTarget), 0.75)
        || !nearlyEqual(sourceUnitPosition(0.5, source, zoomedTarget), 0.5)
        || !nearlyEqual(sourceUnitPosition(0.0, source, zoomedTarget), 0.25)
        || !nearlyEqual(sourceUnitPosition(1.0, source, zoomedTarget), 0.75)) {
        return fail("frequency frame mapping is incorrect");
    }
    if (sourceUnitPosition(1.0, source, FrequencyFrame{14.2, 0.2}) <= 1.0) {
        return fail("newly exposed frequency should map outside the retained frame");
    }

    const FrequencyFrame vhfBase{146.520000, 0.005};
    const FrequencyFrame vhfTarget{146.520375, 0.0025};
    const FrequencyPreviewTransform transform = frequencyPreviewTransform(
        vhfBase, vhfTarget);
    if (!transform.valid || !nearlyEqual(transform.scale, 0.5)
        || !nearlyEqual(transform.offset, 0.075, 1.0e-10)) {
        return fail("preview transform lost narrow-band VHF precision");
    }
    const double sourceU = sourceUnitPosition(0.37, vhfBase, vhfTarget);
    const double shaderEquivalent = 0.5 + transform.offset
        + (0.37 - 0.5) * transform.scale;
    if (!nearlyEqual(sourceU, shaderEquivalent, 1.0e-10)) {
        return fail("CPU and shader preview transforms diverged");
    }
    if (!std::isnan(sourceUnitPosition(
            0.5, FrequencyFrame{14.0, 0.0}, vhfTarget))) {
        return fail("invalid source frame should fail closed");
    }
    if (FrequencyFrame{std::numeric_limits<double>::infinity(), 0.2}.isValid()
        || FrequencyFrame{14.0, std::numeric_limits<double>::infinity()}
               .isValid()) {
        return fail("non-finite frequency frames should be rejected");
    }
    return 0;
}

int testCommandThrottle()
{
    using namespace AetherSDR;
    FrequencyRangeCommandThrottle throttle;
    const FrequencyRangeCommand first{14.0, 0.2};
    const FrequencyRangeCommand intermediate{14.01, 0.18};
    const FrequencyRangeCommand latest{14.02, 0.16};
    const FrequencyRangeCommand final{14.03, 0.14};

    const std::optional<FrequencyRangeCommand> emittedFirst =
        throttle.request(first, true, false);
    if (!emittedFirst.has_value() || throttle.hasPending()) {
        return fail("first due command should emit immediately");
    }
    if (throttle.request(intermediate, false, false).has_value()
        || throttle.request(latest, false, false).has_value()
        || !throttle.hasPending()) {
        return fail("intermediate commands should coalesce");
    }
    const std::optional<FrequencyRangeCommand> emittedFinal =
        throttle.request(final, false, true);
    if (!emittedFinal.has_value()
        || !nearlyEqual(emittedFinal->centerMhz, final.centerMhz)
        || throttle.hasPending()
        || throttle.takePending().has_value()) {
        return fail("forced release should emit once and cancel delayed output");
    }
    throttle.request(intermediate, false, false);
    throttle.request(latest, false, false);
    const std::optional<FrequencyRangeCommand> timeoutCommand =
        throttle.takePending();
    if (!timeoutCommand.has_value()
        || !nearlyEqual(timeoutCommand->centerMhz, latest.centerMhz)
        || throttle.hasPending()) {
        return fail("timeout should emit only the latest coalesced command");
    }
    if (throttle.request(FrequencyRangeCommand{
            std::numeric_limits<double>::quiet_NaN(), 0.2}, true, false)
            .has_value()) {
        return fail("invalid command should be rejected");
    }
    return 0;
}

int testDssZoomFloorSyncGate()
{
    using namespace AetherSDR;
    DssZoomFloorSyncGate gate;
    if (gate.bandwidthChangeQueued() || gate.waitingForFreshFrame()
        || gate.consumeFreshFrame(true)) {
        return fail("3D zoom floor synchronization should start idle");
    }

    gate.noteBandwidthChange();
    if (!gate.bandwidthChangeQueued() || gate.waitingForFreshFrame()
        || gate.consumeFreshFrame(true)) {
        return fail("3D zoom floor synchronization must wait for settle");
    }

    gate.settle(false);
    if (gate.bandwidthChangeQueued() || gate.waitingForFreshFrame()
        || gate.consumeFreshFrame(true)) {
        return fail("2D or Kiwi zoom must not arm a Flex 3D floor sync");
    }

    gate.noteBandwidthChange();
    gate.noteBandwidthChange();
    gate.settle(true);
    if (gate.bandwidthChangeQueued() || !gate.waitingForFreshFrame()
        || gate.consumeFreshFrame(false)
        || !gate.waitingForFreshFrame()) {
        return fail("coalesced 3D zoom must wait for a usable FFT frame");
    }
    if (!gate.consumeFreshFrame(true) || gate.waitingForFreshFrame()
        || gate.consumeFreshFrame(true)) {
        return fail("only the first usable post-zoom FFT frame may resynchronize");
    }

    gate.noteBandwidthChange();
    gate.settle(true);
    gate.noteBandwidthChange();
    if (!gate.bandwidthChangeQueued() || gate.waitingForFreshFrame()) {
        return fail("a newer zoom must cancel an intermediate armed frame");
    }
    gate.clear();
    if (gate.bandwidthChangeQueued() || gate.waitingForFreshFrame()) {
        return fail("3D zoom floor synchronization should clear completely");
    }
    return 0;
}

int testDssZoomFloorFrameGuards()
{
    using namespace AetherSDR;

    // A frame with every window clear is the one the gate is waiting for.
    DssZoomFloorFrameGuards guards;
    guards.nowMs = 10'000;
    guards.notBeforeMs = 10'000;
    guards.postTxSettleMs = 400;
    if (!dssZoomFloorFrameTrusted(guards)) {
        return fail("a settled post-zoom frame must anchor the 3D floor");
    }

    // The radio needs ~100-300 ms to switch bandwidth. Frames before the hold
    // still carry the pre-zoom encoding; the drag-release path arms with no
    // delay of its own, so this is the only thing keeping them out.
    guards.nowMs = 9'999;
    if (dssZoomFloorFrameTrusted(guards)) {
        return fail("a frame before the bandwidth-switch hold must be rejected");
    }
    guards.nowMs = 10'000;

    // Post-TX AGC recovery (#2117): the first RX frame after unkey reads hot.
    guards.txEndMs = guards.nowMs - 399;
    if (dssZoomFloorFrameTrusted(guards)) {
        return fail("a post-TX AGC transient frame must not anchor the floor");
    }
    guards.txEndMs = guards.nowMs - 400;
    if (!dssZoomFloorFrameTrusted(guards)) {
        return fail("frames past the post-TX window are usable again");
    }
    guards.txEndMs = 0;

    // A y_pixels change still settling decodes bins against the old height.
    guards.scaleSettling = true;
    if (dssZoomFloorFrameTrusted(guards)) {
        return fail("a mis-decoded scale-settling frame must be rejected");
    }
    guards.scaleSettling = false;

    // An open dBm-range rebase can hand the sync reprojected preview bins.
    guards.rebaseActive = true;
    if (dssZoomFloorFrameTrusted(guards)) {
        return fail("reprojected preview bins must never anchor the floor");
    }
    guards.rebaseActive = false;

    // The operator owns the scale while dragging it.
    guards.draggingDbmScale = true;
    if (dssZoomFloorFrameTrusted(guards)) {
        return fail("a zoom sync must not fight an active dBm scale drag");
    }
    guards.draggingDbmScale = false;

    if (!dssZoomFloorFrameTrusted(guards)) {
        return fail("clearing every guard must restore a usable frame");
    }
    return 0;
}

int testWaterfallPipelineSelection()
{
    using namespace AetherSDR;
    WaterfallRowFrameReadiness readiness{
        true, true, true, true, true, true,
    };
    if (chooseWaterfallPipeline(readiness)
        != WaterfallPipelineMode::RowFrequencyFrames) {
        return fail("complete row-frame resources should select the GPU preview");
    }

    bool* stages[] = {
        &readiness.requested,
        &readiness.formatSupported,
        &readiness.textureCreated,
        &readiness.samplerCreated,
        &readiness.bindingsCreated,
        &readiness.pipelineCreated,
    };
    for (bool* stage : stages) {
        *stage = false;
        if (chooseWaterfallPipeline(readiness)
            != WaterfallPipelineMode::Legacy) {
            return fail("any row-frame failure must select the legacy pipeline");
        }
        *stage = true;
    }
    return 0;
}

int testWaterfallScrollProgress()
{
    using namespace AetherSDR;
    if (!nearlyEqual(waterfallScrollProgressRows(0, 40.0f), 0.0)
        || !nearlyEqual(waterfallScrollProgressRows(10, 40.0f), 0.25)
        || !nearlyEqual(waterfallScrollProgressRows(40, 40.0f), 1.0)
        || !nearlyEqual(waterfallScrollProgressRows(80, 40.0f), 1.0)
        || !nearlyEqual(waterfallScrollProgressRows(80, 40.0f, 3.0f), 2.0)
        || !nearlyEqual(waterfallScrollProgressRows(160, 40.0f, 3.0f), 3.0)) {
        return fail("waterfall scrolling should advance one row over one interval");
    }
    if (!nearlyEqual(waterfallScrollProgressRows(-1, 40.0f), 0.0)
        || !nearlyEqual(waterfallScrollProgressRows(10, 0.0f), 0.0)
        || !nearlyEqual(
            waterfallScrollProgressRows(
                10, std::numeric_limits<float>::quiet_NaN()),
            0.0)) {
        return fail("invalid waterfall timing should disable interpolation");
    }
    if (!nearlyEqual(
            waterfallScrollSampleOffsetUnit(0.0f, 1.0f, 100), 0.01, 1.0e-6)
        || !nearlyEqual(
            waterfallScrollSampleOffsetUnit(0.5f, 1.0f, 100), 0.005, 1.0e-6)
        || !nearlyEqual(
            waterfallScrollSampleOffsetUnit(1.0f, 1.0f, 100), 0.0, 1.0e-6)
        || !nearlyEqual(
            waterfallScrollSampleOffsetUnit(1.0f, 3.0f, 100), 0.02, 1.0e-6)
        || !nearlyEqual(
            waterfallScrollSampleOffsetUnit(0.5f, 1.0f, 0), 0.0, 1.0e-6)) {
        return fail("waterfall sample offset should preserve the row handoff");
    }
    return 0;
}

int testDssFftScaleSettleWindow()
{
    using namespace AetherSDR;
    if (!dssFftScaleSettleActive(1000, 1750)
        || dssFftScaleSettleActive(1750, 1750)
        || dssFftScaleSettleActive(1800, 1750)
        || dssFftScaleSettleActive(1000, 0)) {
        return fail("3D FFT scale settling must end exactly at its deadline");
    }
    return 0;
}

int testDssStartupHistoryAvailability()
{
    using namespace AetherSDR;
    // Grid ages are integral (sourceV * rows over a fixed grid) and validRows is
    // an int row count, so at a FULL history availability is strictly binary:
    // populated slots opaque, the rest hidden. No partial values are reachable.
    constexpr float kRows = 96.0f;
    if (!nearlyEqual(dssHistoryAvailability(96.0f, 96.0f, kRows, 0.0f), 0.0)
        || !nearlyEqual(dssHistoryAvailability(95.0f, 96.0f, kRows, 0.0f), 1.0)
        || !nearlyEqual(dssHistoryAvailability(94.0f, 96.0f, kRows, 0.0f), 1.0)
        || !nearlyEqual(dssHistoryAvailability(0.0f, 96.0f, kRows, 0.0f), 1.0)) {
        return fail("3D FFT rear visibility must be binary on a full history");
    }
    // Non-finite input and an empty history both fail closed to hidden.
    if (!nearlyEqual(dssHistoryAvailability(
                         std::numeric_limits<float>::quiet_NaN(), 96.0f,
                         kRows, 0.0f),
                     0.0)
        || !nearlyEqual(dssHistoryAvailability(0.0f, 0.0f, kRows, 0.0f), 0.0)
        || !nearlyEqual(dssHistoryAvailability(0.0f, 96.0f, kRows,
                                              std::numeric_limits<float>::
                                                  quiet_NaN()),
                        0.0)) {
        return fail("3D FFT rear visibility must fail closed on bad input");
    }
    // THE regression this guards (#4476): on a full history the oldest slot is
    // permanently populated, so its opacity must not depend on where the scroll
    // clock happens to be. Reinstating the advance term unconditionally makes
    // this ramp 0 -> 1 and snap back on every delayed arrival — the rear pulse.
    for (const float remainingRows : {0.0f, 0.25f, 0.5f, 1.0f, 3.0f}) {
        if (!nearlyEqual(
                dssHistoryAvailability(95.0f, 96.0f, kRows, remainingRows),
                1.0)) {
            return fail("3D FFT rear visibility must not pulse with scroll "
                        "latency on a full history");
        }
    }
    // While the history is still FILLING, the newest slot is genuinely new and
    // dssRetainedSampleAge() clamps it onto its neighbour's row for one
    // interval, so it must fade in over that interval rather than popping a
    // duplicate curtain opaque. Dropping the advance term in this regime makes
    // all three of these 1.0.
    constexpr float kFilling = 10.0f;   // 10 of 96 rows populated
    if (!nearlyEqual(dssHistoryAvailability(9.0f, kFilling, kRows, 1.0f), 0.0)
        || !nearlyEqual(dssHistoryAvailability(9.0f, kFilling, kRows, 0.5f), 0.5)
        || !nearlyEqual(dssHistoryAvailability(9.0f, kFilling, kRows, 0.0f),
                        1.0)) {
        return fail("3D FFT newest rear slot must fade in while history fills");
    }
    // ...and only the newest slot fades: settled slots behind it stay opaque
    // regardless of the scroll clock, and unpopulated ones stay hidden.
    if (!nearlyEqual(dssHistoryAvailability(8.0f, kFilling, kRows, 1.0f), 1.0)
        || !nearlyEqual(dssHistoryAvailability(0.0f, kFilling, kRows, 1.0f), 1.0)
        || !nearlyEqual(dssHistoryAvailability(10.0f, kFilling, kRows, 0.0f),
                        0.0)) {
        return fail("3D FFT fill fade must apply only to the newest slot");
    }
    // The visibility edge and the height path must agree about what exists: on
    // a full history a slot is visible exactly when it has a retained sample.
    for (const float sourceAge : {0.0f, 1.0f, 94.0f, 95.0f, 96.0f, 97.0f}) {
        const bool visible =
            dssHistoryAvailability(sourceAge, 96.0f, kRows, 0.0f) > 0.0f;
        const bool hasSample =
            dssRetainedSampleAge(sourceAge, 0.0f, 96.0f, kRows).has_value();
        if (visible != hasSample) {
            return fail("3D FFT rear visibility must agree with the height "
                        "path's valid-range early-out");
        }
    }
    const std::optional<float> movingAge =
        dssRetainedSampleAge(94.0f, 0.5f, 96.0f, 96.0f);
    const std::optional<float> oldestAge =
        dssRetainedSampleAge(95.0f, 1.0f, 96.0f, 96.0f);
    if (!movingAge || !nearlyEqual(*movingAge, 94.5)
        || !oldestAge || !nearlyEqual(*oldestAge, 95.0)
        || dssRetainedSampleAge(96.0f, 0.0f, 96.0f, 96.0f).has_value()) {
        return fail("3D FFT rear row should remain stable until eviction");
    }
    // The oldest slot's SAMPLE age is clamped to oldestRetainedAge, so it holds
    // still under any scroll phase — this is the clamp that also makes it
    // duplicate its neighbour for one interval while the history fills, which
    // is why the fill fade above exists.
    for (const float remainingRows : {0.0f, 0.5f, 1.0f, 4.0f}) {
        const std::optional<float> clampedAge =
            dssRetainedSampleAge(95.0f, remainingRows, 96.0f, 96.0f);
        if (!clampedAge || !nearlyEqual(*clampedAge, 95.0)) {
            return fail("3D FFT oldest retained sample age must not move with "
                        "scroll latency");
        }
    }
    // Fidelity to the shader's two clamps outside 1 <= validRows <= rows:
    // validRows > rows caps to rows (oldest age = rows - 1, not validRows - 1);
    // 0 < validRows < 1 floors the oldest age at 0 rather than going negative.
    // validRows = 200 > rows caps the oldest age to rows - 1 = 95, so a
    // sourceAge+remainingRows of 100 clamps to 95 (an uncapped mirror would
    // return 100 against validRows - 1 = 199).
    const std::optional<float> cappedAge =
        dssRetainedSampleAge(90.0f, 10.0f, 200.0f, 96.0f);
    // 0 < validRows < 1 floors the oldest age at 0 rather than going negative.
    const std::optional<float> flooredAge =
        dssRetainedSampleAge(0.0f, 0.0f, 0.5f, 96.0f);
    if (!cappedAge || !nearlyEqual(*cappedAge, 95.0)
        || !flooredAge || !nearlyEqual(*flooredAge, 0.0)) {
        return fail("3D FFT retained sample age must match shader clamps");
    }
    return 0;
}

int testObservedWaterfallCadence()
{
    using namespace AetherSDR;
    ObservedWaterfallCadence cadence;
    StablePresentationAnchor timeScaleAnchor;
    if (observeWaterfallCadenceAndTimeScale(
            cadence, timeScaleAnchor, 1000)
        || cadence.valid
        || !nearlyEqual(observedWaterfallMsPerRow(cadence, 75.0f), 75.0)
        || !nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                true, 82.0f, &timeScaleAnchor, 75.0f),
            75.0)) {
        return fail("first waterfall row should only seed cadence timing");
    }
    if (!observeWaterfallCadenceAndTimeScale(
            cadence, timeScaleAnchor, 1100)
        || !cadence.valid
        || !nearlyEqual(cadence.msPerRow, 100.0)
        || timeScaleAnchor.locked
        || !nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                true, 82.0f, &timeScaleAnchor),
            100.0)) {
        return fail("second waterfall row should establish observed cadence");
    }
    if (!observeWaterfallCadenceAndTimeScale(
            cadence, timeScaleAnchor, 1220)
        || !nearlyEqual(cadence.msPerRow, 110.0)
        || timeScaleAnchor.locked
        || !nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                true, 82.0f, &timeScaleAnchor),
            100.0)) {
        return fail("waterfall cadence should smooth ordinary arrival jitter");
    }
    if (observeWaterfallCadenceAndTimeScale(
            cadence, timeScaleAnchor, 1220)
        || !nearlyEqual(cadence.msPerRow, 110.0)) {
        return fail("duplicate waterfall timestamps must not change cadence");
    }
    if (!observeWaterfallCadenceAndTimeScale(
            cadence, timeScaleAnchor, 1360)
        || !nearlyEqual(cadence.msPerRow, 125.0)
        || !timeScaleAnchor.locked
        || !nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                true, 82.0f, &timeScaleAnchor),
            112.0)) {
        return fail("Kiwi time scale should lock after startup acquisition");
    }
    if (!observeWaterfallCadenceAndTimeScale(
            cadence, timeScaleAnchor, 1560)
        || !nearlyEqual(cadence.msPerRow, 140.0)
        || !nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                true, 82.0f, &timeScaleAnchor),
            112.0)) {
        return fail("arrival jitter must not move the locked Kiwi time scale");
    }
    if (!nearlyEqual(
            selectedWaterfallMsPerRow(false, 82.0f, &cadence), 82.0)
        || !nearlyEqual(
            selectedWaterfallMsPerRow(true, 82.0f, &cadence), 140.0)
        || !nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                false, 82.0f, &timeScaleAnchor),
            82.0)
        || !nearlyEqual(
            selectedWaterfallMsPerRow(
                true, 82.0f, nullptr, 95.0f),
            95.0)
        || !nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                true, 82.0f, nullptr, 95.0f),
            95.0)) {
        return fail("Kiwi cadence selection must not alter Flex timing");
    }

    cadence = ObservedWaterfallCadence{};
    if (!nearlyEqual(
            selectedWaterfallTimeScaleMsPerRow(
                true, 82.0f, &timeScaleAnchor),
            112.0)) {
        return fail("Kiwi stream resets must preserve the locked time scale");
    }
    observeWaterfallCadence(cadence, 2000);
    if (!observeWaterfallCadence(cadence, 7000)
        || !nearlyEqual(cadence.msPerRow, 5000.0)) {
        return fail("slow Kiwi waterfall rates must retain their full interval");
    }
    return 0;
}

int testStablePresentationAnchor()
{
    using namespace AetherSDR;
    StablePresentationAnchor anchor;
    if (observeStablePresentationAnchor(
            anchor, std::numeric_limits<float>::quiet_NaN())
        || anchor.hasValue) {
        return fail("presentation anchors must reject invalid samples");
    }
    if (!observeStablePresentationAnchor(anchor, -101.1f, 3, 0.5f)
        || !anchor.hasValue
        || anchor.locked
        || !nearlyEqual(
            stablePresentationValue(anchor, -90.0f), -101.1, 1.0e-4)) {
        return fail("first presentation sample should establish a fixed provisional value");
    }
    if (!observeStablePresentationAnchor(anchor, -99.9f, 3, 0.5f)
        || anchor.locked
        || !nearlyEqual(
            stablePresentationValue(anchor, -90.0f), -101.1, 1.0e-4)) {
        return fail("presentation acquisition should not move the provisional axis");
    }
    if (!observeStablePresentationAnchor(anchor, -100.2f, 3, 0.5f)
        || !anchor.locked
        || !nearlyEqual(stablePresentationValue(anchor, -90.0f), -100.5)) {
        return fail("presentation anchor should lock to a quantized acquisition mean");
    }
    if (observeStablePresentationAnchor(anchor, -80.0f, 3, 0.5f)
        || !nearlyEqual(stablePresentationValue(anchor, -90.0f), -100.5)) {
        return fail("locked presentation anchors must ignore live measurement drift");
    }
    return 0;
}

} // namespace

int main()
{
    if (const int result = testCursorAnchoredZoom(); result != 0) {
        return result;
    }
    if (const int result = testFrequencyFrameMapping(); result != 0) {
        return result;
    }
    if (const int result = testCommandThrottle(); result != 0) {
        return result;
    }
    if (const int result = testDssZoomFloorSyncGate(); result != 0) {
        return result;
    }
    if (const int result = testDssZoomFloorFrameGuards(); result != 0) {
        return result;
    }
    if (const int result = testWaterfallPipelineSelection(); result != 0) {
        return result;
    }
    if (const int result = testWaterfallScrollProgress(); result != 0) {
        return result;
    }
    if (const int result = testDssFftScaleSettleWindow(); result != 0) {
        return result;
    }
    if (const int result = testDssStartupHistoryAvailability(); result != 0) {
        return result;
    }
    if (const int result = testObservedWaterfallCadence(); result != 0) {
        return result;
    }
    return testStablePresentationAnchor();
}
