#include "ota_uart_tune.h"

uint16_t ota_uart_tune_chunk_for_baud(int baud)
{
    if (baud <= 0) {
        return OTA_FRAME_DATA_CHUNK_RECOMMEND;
    }

    /*
     * chunk ≈ baud/512 - wire_overhead：高波特率大块，减少 USB 往返次数。
     * 115200→~201B，460800→~876B，921600→顶满 MAX（通常 1024）。
     */
    int64_t chunk = (int64_t)baud / 512 - OTA_UART_WIRE_OVERHEAD_BYTES;
    if (chunk < 32) {
        chunk = 32;
    }
    if (chunk > OTA_FRAME_MAX_PAYLOAD) {
        chunk = OTA_FRAME_MAX_PAYLOAD;
    }
    return (uint16_t)chunk;
}

uint32_t ota_uart_tune_ack_timeout_ms(int baud, uint16_t chunk)
{
    if (baud <= 0) {
        baud = 115200;
    }

    uint32_t wire_ms = (uint32_t)(((uint64_t)(chunk + OTA_UART_WIRE_OVERHEAD_BYTES) * 10 * 1000) /
                                  (uint32_t)baud);
    uint32_t t = wire_ms * 3 + 800;
    if (t < 1200) {
        t = 1200;
    }
    if (t > 8000) {
        t = 8000;
    }
    return t;
}

uint32_t ota_uart_tune_transfer_idle_ms(int baud)
{
    uint16_t chunk = ota_uart_tune_chunk_for_baud(baud);
    uint32_t t = ota_uart_tune_ack_timeout_ms(baud, chunk) + 1000;
    if (t < 2000) {
        t = 2000;
    }
    if (t > 12000) {
        t = 12000;
    }
    return t;
}
