#pragma once
#include <cstddef>
#include <cstdint>

#include "voice_recording_store.h"
#include "voice_upload_policy.h"

constexpr uint64_t VOICE_MIN_RECORDING_MS = 1000;
inline bool voice_recording_too_short(uint64_t started, uint64_t released) {
    return !started || released < started || released-started <= VOICE_MIN_RECORDING_MS;
}

constexpr unsigned VOICE_CAPTURE_FRAME_MS = 40;
// PCM no longer traverses this queue; it carries control frames only, so a
// stalled transport can never overflow it and abort an otherwise valid capture.
constexpr unsigned VOICE_CAPTURE_QUEUE_FRAMES = VOICE_CONTROL_QUEUE_FRAMES;
constexpr unsigned VOICE_SEND_TIMEOUT_MS = 2000;

// Upload progress is a property of the transfer, never of the recording phase.
// While the user is still holding A the UI must stay in RECORDING, so progress
// is only reported once capture has stopped (a terminal END frame was seen).
inline bool voice_should_report_progress(bool capture_finished) {
    return capture_finished;
}

// Percent acknowledged. 100 is reserved for a received upload, so a transfer
// that is still in flight can never paint a finished bar.
inline int voice_upload_percent(size_t uploaded_bytes, size_t total_bytes) {
    if (total_bytes == 0) return 0;
    if (uploaded_bytes >= total_bytes) return 99;
    return int(100 * uploaded_bytes / total_bytes);
}

constexpr unsigned VOICE_PCM_BYTES_PER_SECOND = 44100 * 2;
// Recording length is frozen when capture stops; it is never derived from how
// long an interrupted upload took. The byte count is authoritative, the clock
// only bounds it when the codec path stopped early.
inline uint64_t voice_recorded_duration_ms(size_t recorded_bytes, uint64_t clock_ms) {
    const uint64_t by_bytes = uint64_t(recorded_bytes) * 1000 / VOICE_PCM_BYTES_PER_SECOND;
    if (!clock_ms) return by_bytes;
    return by_bytes < clock_ms ? by_bytes : clock_ms;
}

// One chunk is uploaded and acknowledged at a time; a blocked write delays the
// next chunk, never the microphone.
static_assert(VOICE_CAPTURE_QUEUE_FRAMES >= 4,
              "Control queue must hold START, progress, and a terminal frame");
static_assert(VOICE_MAX_RECORDING_BYTES == 1764000,
              "20 s of 44.1 kHz 16-bit mono must remain the recording cap");