/*
 * dialer.c — Digit accumulator for the PLIP telephone state machine.
 *
 * Digits are pushed from two sources:
 *   1. HTTP /debug/dial?number=NNNN  (net.c handler)
 *   2. Rotary pulse detection (phone.c, CONFIG_PLIP_DIAL_PULSE)
 *
 * Thread-safety: all state is protected by atomic operations on s_last_us
 * and simple writes to s_len / s_num (called from a single phone task or
 * HTTP task at a time — no concurrent push expected).
 */

#include "dialer.h"

#include "esp_log.h"
#include "esp_timer.h"

#include <string.h>
#include <stdint.h>

#define TAG "dialer"

#define MAX_DIGITS 12

static char    s_num[MAX_DIGITS + 1];
static int     s_len;
static int64_t s_last_us;  /* esp_timer_get_time() at last push */

void dialer_init(void)
{
    memset(s_num, 0, sizeof(s_num));
    s_len     = 0;
    s_last_us = 0;
    ESP_LOGI(TAG, "dialer init");
}

void dialer_push_digit(int d)
{
    if (d < 0 || d > 9) return;
    if (s_len >= MAX_DIGITS) return;  /* silently discard overflow */

    s_num[s_len++] = (char)('0' + d);
    s_num[s_len]   = '\0';
    s_last_us      = esp_timer_get_time();

    ESP_LOGI(TAG, "digit %d -> number so far: \"%s\"", d, s_num);
}

void dialer_reset(void)
{
    memset(s_num, 0, sizeof(s_num));
    s_len     = 0;
    s_last_us = 0;
    ESP_LOGI(TAG, "dialer reset");
}

const char *dialer_current(void)
{
    return s_num;
}

bool dialer_idle(void)
{
    return s_len == 0;
}

int dialer_ms_since_last(void)
{
    if (s_last_us == 0) return 0;
    int64_t elapsed_us = esp_timer_get_time() - s_last_us;
    int ms = (int)(elapsed_us / 1000);
    return (ms < 0) ? 0 : ms;
}
