// card_meta — pure implementation. See card_meta.h. NO REAPER / SWELL / LICE / vendor.

#include "card_meta.h"

#include <cmath>
#include <cstdio>

namespace reasampler {

std::string formatBarsBeats(const MusicalLength& m) {
    // No derivable musical read-out without a positive tempo AND a stamped meter.
    if (m.tempoBpm <= 0.0 || m.timeSigNum <= 0 || m.timeSigDenom <= 0) return {};

    const double len = m.lengthSeconds > 0.0 ? m.lengthSeconds : 0.0;

    // Total beats in THIS meter. A quarter-note is 60/tempo s; a beat is (4/denom)
    // quarter-notes, so a beat lasts (60/tempo) * (4/denom) seconds. beats = len / that.
    const double secondsPerBeat = (60.0 / m.tempoBpm) * (4.0 / m.timeSigDenom);
    double totalBeats = len / secondsPerBeat;

    // Snap to an exact beat when we are within a hundredth-of-a-beat epsilon of one, so a
    // bar-aligned capture reads "2.1.00" rather than "1.4.99" from FP error just under the
    // boundary. The epsilon is well below the .01 display quantum, so it never mis-rounds a
    // genuinely fractional length.
    const double snapped = std::floor(totalBeats + 0.5);
    if (std::fabs(totalBeats - snapped) < 1e-6) totalBeats = snapped;

    // Split into whole beats + a fractional remainder (0..1 of a beat).
    double wholeBeats = std::floor(totalBeats);
    double frac = totalBeats - wholeBeats;

    // Bars/beats are 1-based; beat cycles 1..timeSigNum within a bar.
    const long wb = static_cast<long>(wholeBeats);
    const long bar  = wb / m.timeSigNum + 1;       // 1-based bar
    const long beat = wb % m.timeSigNum + 1;       // 1-based beat within the bar

    // Subdivision: hundredths of a beat, floored (0..99). A decorative display quantum.
    int sub = static_cast<int>(std::floor(frac * 100.0));
    if (sub < 0) sub = 0;
    if (sub > 99) sub = 99;

    char buf[48];
    std::snprintf(buf, sizeof(buf), "%ld.%ld.%02d", bar, beat, sub);
    return buf;
}

std::string formatSecondsMs(double lengthSeconds) {
    double len = lengthSeconds > 0.0 ? lengthSeconds : 0.0;

    long secs = static_cast<long>(std::floor(len));
    // Round to the nearest millisecond (not floor): FP error means 62.037 s stores as
    // 62.0369999... and a raw floor would render "62.036". +0.5 before truncation rounds
    // to the closest ms, which is what a wall-clock read-out should show.
    int ms = static_cast<int>((len - static_cast<double>(secs)) * 1000.0 + 0.5);
    // Rounding can push ms to 1000 at a whole-second boundary; carry into seconds.
    if (ms >= 1000) { ms -= 1000; ++secs; }
    if (ms < 0) ms = 0;

    char buf[48];
    std::snprintf(buf, sizeof(buf), "%ld.%03d", secs, ms);
    return buf;
}

} // namespace reasampler
