// Lapper v2: weighing dog-bowl stand. Atech 14-port board (ESP32-S3), HX711 on port 10,
// Electrokit 5 kg bar cell, up to FIVE Atech LED grids (NeoPixel 3x3, 9 px each) lighting the
// clear-PETG platter from inside: four plugged straight onto the board's sockets facing up
// (ports 3-6) and one on the 80 mm cable lying flat in the floor at the front (port 2).
//
// What it does
//   - Weighs the bowl continuously (10 Hz), same HX711 chain + filters as the Atech scale firmware.
//   - Learns the EMPTY BOWL weight itself: the lowest stable weight it has ever seen above the
//     bare-platter zero is the bowl. (Bare platter = TARE, done once at assembly.)
//   - Water grams = total - bowl. Full / low / empty thresholds in grams (1 g = 1 ml).
//   - Drinking sessions: a stable-to-stable drop while a dog is at the bowl (weight noisy, then
//     lower) is logged as one drink in ml. Splashes and paws (weight UP then back) are ignored.
//   - 2.2: the LIGHT IS THE PLATTER. The whole platter and the bowl on it glow: soft warm white
//     when fine (AMBIENT <pct>), 1.5x brighter while a dog drinks, faint blue when the bowl is
//     lifted, amber breathing when low, red pulse when empty. GLOW 0 is the master switch.
//     NIGHT <on_h> <off_h> turns the ambient glow off between those hours (alerts still show);
//     there is no RTC, so the app sends TIME <hh:mm> at connect and the firmware counts from there.
//     Power cap: 45 pixels x 3 channels x 20 mA = 2.7 A at full white, the board's 5 V rail is
//     the grids run on the 3.3 V rail (500 mA), so every grid runs under setBrightness(BRIGHT_CAP = 45) -> 17.6 %, <= 0.48 A worst case.
//   - 2.1: per-dog intake. DOG <kg> once; every drink and the 2 Hz line then carry ml/kg for the
//     day. At the 24 h rollover a "day" event sums the day, flags polydipsia (> 100 ml/kg/day) or
//     near-zero intake (< 20 ml/kg/day) and compares it with a 7-day ring kept in NVS (HISTORY).
//     Thresholds and the ml/kg framing come from docs/RESEARCH.md [S14], [S15].
//
// Serial protocol (JSON lines, 115200):
//   out: {"g":1234.5,"water_ml":812,"bowl_g":422,"state":"ok|low|empty|drinking|lifted","stable":1,
//         "cal":1,"ml_per_kg_today":34.3}                       (ml_per_kg_today only when DOG is set)
//        {"event":"drink","ml":63,"secs":9,"today_ml":412,"ml_per_kg_today":34.3}
//        {"event":"day","ml":640,"ml_per_kg":53.3,"drinks":11,"flag":"ok|high|low|unknown",
//         "avg7_ml":610,"trend":"up|flat|down"}                (trend only when DOG is set)
//        {"event":"history","days_ml":[...oldest..newest],"avg_ml":610}   (avg of non-zero days, else null)
//        {"event":"boot"|"tared"|"calibrated"|"bowl_learned"|"status"|"error", ...}
//        status carries "ambient":40,"night":1|0,"night_on":22,"night_off":7,"clock":"hh:mm"|null,"grids":5
//   in : TARE | CAL <g> | FACTOR <cpg> | BOWL <g> | LEVELS <low_ml> <empty_ml> | GLOW 0|1 | DOG <kg>
//        | AMBIENT <pct> | NIGHT <on_hour> <off_hour> | TIME <hh:mm> | HISTORY | STATUS | HELP
#include <Arduino.h>
#include <Preferences.h>
#include <Adafruit_NeoPixel.h>
#include <math.h>
#include "speaker.h"            // Atech speaker module driver (MAX98357A over I2S), copied from atech_docs
#include "voice_need_water.h"   // "Need water. Need water." 16 kHz PCM, scripts/make_voice.py
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include "webpage.h"            // the on-device page (bowl WiFi + home LAN)

#ifndef HX_PORT_SCK
#define HX_PORT_SCK 2
#endif
#ifndef HX_PORT_DOUT
#define HX_PORT_DOUT 1
#endif
#ifndef LED_PIN_A
#define LED_PIN_A 9
#endif
#ifndef LED_PIN_B
#define LED_PIN_B 8
#endif
// The four grids seated on the board: ports 2, 5, 9, 13 (Data A / Data B GPIOs from atech_docs
// 14_port.md). Both lines are driven per grid because the RGB rev listens on A and the RGBW rev on B.
// -1 = not fitted.
#ifndef LED_P2_A
#define LED_P2_A 5
#endif
#ifndef LED_P2_B
#define LED_P2_B 4
#endif
#ifndef LED_P5_A
#define LED_P5_A 11
#endif
#ifndef LED_P5_B
#define LED_P5_B 10
#endif
#ifndef LED_P9_A
#define LED_P9_A 40
#endif
#ifndef LED_P9_B
#define LED_P9_B 41
#endif
#ifndef LED_P13_A
#define LED_P13_A 39
#endif
#ifndef LED_P13_B
#define LED_P13_B 38
#endif
// Speaker on ports 3 + 4. A two-port module seated on the LEFT column has its first header (LRCLK / BCLK)
// on the HIGHER port number (module x runs toward lower z there, atech_module_renders/NOTES.md), so:
// port 4 Data A = LRCLK (16), port 4 Data B = BCLK (15), port 3 Data B = DIN (18). Bench-found 2026-09-07.
#ifndef SPK_LRCLK
#define SPK_LRCLK 16
#endif
#ifndef SPK_BCLK
#define SPK_BCLK 15
#endif
#ifndef SPK_DIN
#define SPK_DIN 18
#endif
#define FW_VERSION "lapper/2.6"
#ifndef DAY_MS
#define DAY_MS 86400000UL                           // bench builds: -DDAY_MS=60000 forces a rollover every minute
#endif

// ---- signal chain (from atech_scale, verified numbers) -------------------------------
static const float DEFAULT_COUNTS_PER_G = 430.0f;   // 1.0 mV/V cell, HX711 gain 128, ratiometric
static const int   MEDIAN_N = 5;
static const float EMA_ALPHA = 0.35f;
static const int   STABLE_N = 10;                   // 1.0 s window at 10 Hz
static const float STABLE_G = 1.5f;                 // dog bowl: 1.5 g p-p is "still"
static const unsigned long HX_TIMEOUT_MS = 500;

// ---- bowl logic -------------------------------------------------------------------------
static const float MIN_BOWL_G   = 80.0f;    // anything lighter than this is not a bowl (paw, splash)
static const float LIFT_G       = 30.0f;    // total below this = bowl lifted off
static const float DRINK_MIN_ML = 8.0f;     // smallest drop that counts as a drink
static const unsigned long DRINK_GAP_MS = 4000;   // quiet time that closes a drinking session
float lowMl = 250.0f, emptyMl = 60.0f;      // defaults for a ~1.5 L bowl; LEVELS changes them

// ---- daily intake (docs/RESEARCH.md [S14], [S15]) ----------------------------------------
// Vets: a healthy adult dog drinks ~50-60 ml/kg/day (40-60 by activity); > 100 ml/kg/day is the
// definition of polydipsia (CKD, Cushing's, diabetes). Owners notice abnormal drinking months
// before a diagnosis, so the day summary is flagged in ml/kg and compared with the 7-day mean.
static const float POLYDIPSIA_ML_PER_KG = 100.0f;   // flag "high" above this            [S15]
static const float LOW_INTAKE_ML_PER_KG = 20.0f;    // flag "low" below this: drank almost nothing all day
static const float TREND_PCT            = 25.0f;    // "up"/"down" when today differs from the 7-day mean by more than this
static const float DOG_KG_MIN = 0.5f, DOG_KG_MAX = 100.0f;
static const int   HIST_N = 7;                      // ring of the last 7 daily totals (ml)

Preferences prefs;
float scaleFactor = DEFAULT_COUNTS_PER_G; long tareOffset = 0; bool calibrated = false;
float bowlG = 0.0f; bool bowlKnown = false; bool glowEnabled = true;

// ---- light ----------------------------------------------------------------------------------
// Power cap. 5 grids x 9 px = 45 pixels x 3 channels x 20 mA = 2700 mA at full white. The board's
// 5 V rail is 1 A. setBrightness(77) scales every channel by 77/255 = 30.2 %:
// 2700 mA x 77/255 = 815 mA worst case (all 45 pixels white), under the rail and under the
// 0.85 A limit in docs/TEST.md row 15. Applied to every strip at boot, never raised anywhere.
static const uint8_t BRIGHT_CAP = 45;                // 17.6 %: five grids peak 5 x 540 mA = 2.7 A on the 3.3 V rail (500 mA) -> <= 0.48 A
static const int     GRID_PX    = 9;                // one Atech LED grid is 3x3
static const uint8_t AMBIENT_R = 255, AMBIENT_G = 160, AMBIENT_B = 70;   // soft warm white at 100 %
static const float   DRINK_GAIN = 1.5f;             // ambient x1.5 while a dog drinks (clamped to 100 %)
uint8_t ambientPct = 40;                            // AMBIENT <pct>: 0..100 % of the cap when the bowl is ok
uint8_t nightOn = 0, nightOff = 0;                  // NIGHT <on_hour> <off_hour>; on == off = disabled
bool clockKnown = false;                            // TIME <hh:mm> received since boot?
uint16_t clockMin = 0; unsigned long clockSetMs = 0;   // minute-of-day at clockSetMs, advanced from millis()

long medBuf[MEDIAN_N]; int medIdx = 0, medFill = 0;
float ema = 0; bool emaInit = false;
float stabBuf[STABLE_N]; int stabIdx = 0, stabFill = 0;
bool hxPresent = true; unsigned long sampleCount = 0, saturatedCount = 0;

// drinking-session state
float lastStableG = NAN;          // last stable total
float sessionStartG = NAN;        // stable weight before the bowl went unstable
unsigned long unstableSince = 0, lastUnstableMs = 0;
bool inSession = false;
float todayMl = 0; unsigned long dayStartMs = 0;
uint32_t todayDrinks = 0;                           // drinks counted since the last rollover
float dogKg = 0.0f;                                 // DOG <kg>; 0 = unknown
float histMl[HIST_N]; uint8_t histIdx = 0;          // histIdx = next slot to write = oldest day

// Port-1 grid on the cable: the RGB rev listens on Line A, the RGBW rev on Line B, so both are
// driven and whichever rev is plugged in answers. Same for each on-board grid: one A strip + one B strip.
Adafruit_NeoPixel ledA(GRID_PX, LED_PIN_A, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel ledB(GRID_PX, LED_PIN_B, NEO_GRBW + NEO_KHZ800);
static const int ONBOARD_A[4] = { LED_P2_A, LED_P5_A, LED_P9_A, LED_P13_A };
static const int ONBOARD_B[4] = { LED_P2_B, LED_P5_B, LED_P9_B, LED_P13_B };
Adafruit_NeoPixel *onboard[8]; bool onboardW[8]; int onboardN = 0;   // built in setup(): A (RGB) and B (RGBW) strip per fitted port
int onboardPorts = 0;
int gridCount() { return 1 + onboardPorts; }        // fitted grids (the cable grid counts once)

// ---- HX711 bit-bang (channel A, gain 128) ---------------------------------------------
static inline bool hxReady() { return digitalRead(HX_PORT_DOUT) == LOW; }
long hxReadRaw() {
    uint32_t v = 0;
    noInterrupts();
    for (int i = 0; i < 24; i++) {
        digitalWrite(HX_PORT_SCK, HIGH); delayMicroseconds(1);
        v = (v << 1) | (digitalRead(HX_PORT_DOUT) ? 1u : 0u);
        digitalWrite(HX_PORT_SCK, LOW); delayMicroseconds(1);
    }
    digitalWrite(HX_PORT_SCK, HIGH); delayMicroseconds(1); digitalWrite(HX_PORT_SCK, LOW);
    interrupts();
    if (v & 0x800000u) v |= 0xFF000000u;
    return (long)(int32_t)v;
}
unsigned long lastReady = 0;                        // last time DOUT went low (loop() and the blocking reads both feed it)
bool hxReadBlocking(long &out, unsigned long timeoutMs = HX_TIMEOUT_MS) {
    unsigned long t0 = millis();
    while (!hxReady()) { if (millis() - t0 > timeoutMs) return false; delay(1); }
    out = hxReadRaw(); lastReady = millis(); return true;
}
bool hxAverage(int n, long &avg) {
    long long sum = 0;
    for (int i = 0; i < n; i++) { long v; if (!hxReadBlocking(v)) return false; sum += v; }
    avg = (long)(sum / n); return true;
}
long medianOf(long *buf, int n) {
    long tmp[MEDIAN_N]; for (int i = 0; i < n; i++) tmp[i] = buf[i];
    for (int i = 1; i < n; i++) { long k = tmp[i]; int j = i - 1; while (j >= 0 && tmp[j] > k) { tmp[j + 1] = tmp[j]; j--; } tmp[j + 1] = k; }
    return tmp[n / 2];
}
void resetFilters() { medIdx = medFill = 0; emaInit = false; stabIdx = stabFill = 0; }
float rawToGrams(long raw) { return (float)(raw - tareOffset) / scaleFactor; }

// ---- NVS ------------------------------------------------------------------------------
bool voiceEnabled = true; uint8_t volumePct = 40;      // VOICE 0|1, VOLUME <pct> (used by the voice block below)
String dogName = "";                                 // NAME <text>: page title + WiFi name
String staSsid = "", staPass = "";                   // WIFI <ssid> <pass> (home network, optional)
void loadPrefs() {
    prefs.begin("lapper", true);
    calibrated = prefs.getBool("calibrated", false);
    scaleFactor = prefs.getFloat("sf0", DEFAULT_COUNTS_PER_G);
    tareOffset = prefs.getLong("off0", 0);
    bowlG = prefs.getFloat("bowl_g", 0); bowlKnown = prefs.getBool("bowl_known", false);
    lowMl = prefs.getFloat("low_ml", lowMl); emptyMl = prefs.getFloat("empty_ml", emptyMl);
    glowEnabled = prefs.getBool("glow", true);
    dogName = prefs.getString("name", ""); staSsid = prefs.getString("ssid", ""); staPass = prefs.getString("pass", "");
    voiceEnabled = prefs.getBool("voice", true); volumePct = prefs.getUChar("volume", 40); if (volumePct > 100) volumePct = 100;
    ambientPct = prefs.getUChar("ambient", 40); if (ambientPct > 100) ambientPct = 100;
    nightOn = prefs.getUChar("night_on", 0) % 24; nightOff = prefs.getUChar("night_off", 0) % 24;
    dogKg = prefs.getFloat("dog_kg", 0.0f);
    for (int i = 0; i < HIST_N; i++) histMl[i] = 0;
    if (prefs.getBytesLength("hist") == sizeof(histMl)) prefs.getBytes("hist", histMl, sizeof(histMl));
    histIdx = prefs.getUChar("hist_i", 0) % HIST_N;
    prefs.end();
    if (!(scaleFactor > 1.0f) || isnan(scaleFactor)) scaleFactor = DEFAULT_COUNTS_PER_G;
    if (isnan(dogKg) || dogKg < DOG_KG_MIN || dogKg > DOG_KG_MAX) dogKg = 0.0f;
    for (int i = 0; i < HIST_N; i++) if (isnan(histMl[i]) || histMl[i] < 0) histMl[i] = 0;
}
void savePrefs() {
    prefs.begin("lapper", false);
    prefs.putBool("calibrated", calibrated); prefs.putFloat("sf0", scaleFactor); prefs.putLong("off0", tareOffset);
    prefs.putFloat("bowl_g", bowlG); prefs.putBool("bowl_known", bowlKnown);
    prefs.putFloat("low_ml", lowMl); prefs.putFloat("empty_ml", emptyMl); prefs.putBool("glow", glowEnabled); prefs.putBool("voice", voiceEnabled); prefs.putString("name", dogName); prefs.putString("ssid", staSsid); prefs.putString("pass", staPass); prefs.putUChar("volume", volumePct);
    prefs.putFloat("dog_kg", dogKg);
    prefs.putUChar("ambient", ambientPct); prefs.putUChar("night_on", nightOn); prefs.putUChar("night_off", nightOff);
    prefs.end();
}
void saveHistory() {   // written once a day, kept apart from savePrefs() so bowl learning does not rewrite the ring
    prefs.begin("lapper", false);
    prefs.putBytes("hist", histMl, sizeof(histMl)); prefs.putUChar("hist_i", histIdx);
    prefs.end();
}
void emitError(const char *msg) { Serial.print("{\"event\":\"error\",\"msg\":\""); Serial.print(msg); Serial.println("\"}"); }

// ---- glow -----------------------------------------------------------------------------
enum State { ST_OK, ST_LOW, ST_EMPTY, ST_DRINKING, ST_LIFTED };
State state = ST_OK;

// ---- web: the bowl's own Wi-Fi and page ----
// SoftAP "Lapper <name>" (open) with a captive portal -> http://192.168.4.1; the same page is served on the
// home LAN once WIFI <ssid> <pass> is saved. /data = last 60 s of samples + status, /cmd?c= runs a serial command.
static const int WEB_N = 120;                       // 60 s at the 2 Hz sample push
struct WebSample { uint32_t t; float g; uint8_t st, stable; } webBuf[WEB_N]; int webIdx = 0, webFill = 0;
String webEvents[16]; int webEvIdx = 0, webEvFill = 0;
float webWaterMl = NAN; bool webStable = false;
WebServer web(80); DNSServer dns; bool webUp = false;
void logEvent(const String &e) { webEvents[webEvIdx] = e; webEvIdx = (webEvIdx + 1) % 16; if (webEvFill < 16) webEvFill++; }
void webPush(float g, State st, bool stable, float waterMl) {
    webBuf[webIdx] = { millis(), g, (uint8_t)st, (uint8_t)(stable ? 1 : 0) }; webIdx = (webIdx + 1) % WEB_N; if (webFill < WEB_N) webFill++;
    webWaterMl = waterMl; webStable = stable;
}

// ---- voice: "Need water. Need water." on a loop for VOICE_MS when the bowl goes empty ---------------
// Once per emptying (re-armed when the bowl reads ok/low again), never at night, stops early if the bowl
// is lifted or refilled. The clip streams from flash through the Atech driver's writeSamples() in its own task.
Speaker speaker(SPK_BCLK, SPK_LRCLK, SPK_DIN);
static const unsigned long VOICE_MS = 30000, VOICE_GAP_MS = 700;
volatile bool voiceRun = false; bool voiceArmed = true; unsigned long voiceStartMs = 0; TaskHandle_t voiceTaskH = NULL;
void voiceTask(void *) {
    while (voiceRun) {
        speaker.writeSamples(VOICE_PCM, VOICE_N);
        for (unsigned long t = 0; t < VOICE_GAP_MS && voiceRun; t += 50) vTaskDelay(pdMS_TO_TICKS(50));
    }
    voiceTaskH = NULL; vTaskDelete(NULL);
}
void voiceStart(const char *why) {
    if (voiceRun) return;
    voiceRun = true; voiceStartMs = millis();
    Serial.print("{\"event\":\"voice\",\"on\":1,\"why\":\""); Serial.print(why); Serial.println("\"}"); logEvent(String("voice: need water (") + why + ")");
    xTaskCreatePinnedToCore(voiceTask, "voice", 4096, NULL, 1, &voiceTaskH, 0);
}
void voiceStop() { if (!voiceRun) return; voiceRun = false; Serial.println("{\"event\":\"voice\",\"on\":0}"); }
void setAll(uint8_t r, uint8_t g, uint8_t b) {   // every fitted grid, same colour; BRIGHT_CAP scales it in show()
    for (int i = 0; i < GRID_PX; i++) { ledA.setPixelColor(i, ledA.Color(r, g, b)); ledB.setPixelColor(i, ledB.Color(r, g, b, 0)); }
    ledA.show(); ledB.show();
    for (int s = 0; s < onboardN; s++) { for (int i = 0; i < GRID_PX; i++) onboard[s]->setPixelColor(i, onboardW[s] ? onboard[s]->Color(r, g, b, 0) : onboard[s]->Color(r, g, b)); onboard[s]->show(); }
}
void setAmbient(float gain) {                     // warm white at ambientPct x gain, clamped to 100 % of the cap
    float k = ambientPct / 100.0f * gain; if (k > 1.0f) k = 1.0f;
    setAll((uint8_t)(AMBIENT_R * k), (uint8_t)(AMBIENT_G * k), (uint8_t)(AMBIENT_B * k));
}
// ---- clock (no RTC: TIME <hh:mm> from the app + millis()) ----------------------------------
int clockNowMin() { return clockKnown ? (int)((clockMin + (millis() - clockSetMs) / 60000UL) % 1440UL) : -1; }
bool isNight() {                                   // true only when TIME was sent and NIGHT is set
    if (!clockKnown || nightOn == nightOff) return false;
    int h = clockNowMin() / 60;
    return nightOn < nightOff ? (h >= nightOn && h < nightOff) : (h >= nightOn || h < nightOff);   // wraps midnight
}
void glowUpdate() {
    static unsigned long last = 0; unsigned long now = millis();
    if (now - last < 40) return; last = now;
    if (!glowEnabled) { setAll(0, 0, 0); return; }
    float t = (now % 3000) / 3000.0f; float breath = 0.5f * (1.0f - cosf(2.0f * PI * t));   // 0..1, 3 s period
    bool night = isNight();                        // ambient off at night; amber / red alerts still show
    switch (state) {
        case ST_LOW:      setAll((uint8_t)(170 + 85 * breath), (uint8_t)(70 + 35 * breath), 0); break;   // amber breathing, whole platter
        case ST_EMPTY:    setAll((uint8_t)(60 + 195 * breath), 0, 0); break;                           // red pulse
        case ST_LIFTED:   if (night) setAll(0, 0, 0); else setAll(0, 0, 40); break;                    // faint blue: bowl is off
        case ST_DRINKING: if (night) setAll(0, 0, 0); else setAmbient(DRINK_GAIN); break;              // brighter while the dog drinks
        default:          if (night) setAll(0, 0, 0); else setAmbient(1.0f); break;                    // ok: soft warm white
    }
}

// ---- weighing + bowl logic ------------------------------------------------------------
const char *stateName(State s) { switch (s) { case ST_OK: return "ok"; case ST_LOW: return "low"; case ST_EMPTY: return "empty"; case ST_DRINKING: return "drinking"; default: return "lifted"; } }

// ---- daily intake ---------------------------------------------------------------------
bool dogKnown() { return dogKg > 0.0f; }
float mlPerKg(float ml) { return dogKnown() ? ml / dogKg : NAN; }
void printMlPerKgToday() {   // appended to drink events and the 2 Hz line; absent when DOG is not set
    if (!dogKnown()) return;
    Serial.print(",\"ml_per_kg_today\":"); Serial.print(mlPerKg(todayMl), 1);
}
float hist7Avg() {   // mean of the non-zero days in the ring, NAN if none
    float sum = 0; int n = 0;
    for (int i = 0; i < HIST_N; i++) if (histMl[i] > 0) { sum += histMl[i]; n++; }
    return n ? sum / n : NAN;
}
void printHistory() {
    Serial.print("{\"event\":\"history\",\"days_ml\":[");
    for (int i = 0; i < HIST_N; i++) { if (i) Serial.print(","); Serial.print(histMl[(histIdx + i) % HIST_N], 0); }   // oldest..newest
    float avg = hist7Avg();
    Serial.print("],\"avg_ml\":"); if (isnan(avg)) Serial.print("null"); else Serial.print(avg, 0); Serial.println("}");
}
const char *intakeFlag(float mlkg) {
    if (isnan(mlkg)) return "unknown";
    if (mlkg > POLYDIPSIA_ML_PER_KG) return "high";
    if (mlkg < LOW_INTAKE_ML_PER_KG) return "low";
    return "ok";
}
void rolloverDay() {   // called at the 24 h mark: summarise, push into the ring, zero the day
    float mlkg = mlPerKg(todayMl);
    histMl[histIdx] = todayMl; histIdx = (histIdx + 1) % HIST_N; saveHistory();
    float avg = hist7Avg();   // last 7 days including today, same number HISTORY reports
    Serial.print("{\"event\":\"day\",\"ml\":"); Serial.print(todayMl, 0);
    Serial.print(",\"ml_per_kg\":"); if (isnan(mlkg)) Serial.print("null"); else Serial.print(mlkg, 1);
    Serial.print(",\"drinks\":"); Serial.print(todayDrinks);
    Serial.print(",\"flag\":\""); Serial.print(intakeFlag(mlkg));
    Serial.print("\",\"avg7_ml\":"); if (isnan(avg)) Serial.print("null"); else Serial.print(avg, 0);
    if (dogKnown()) {
        const char *trend = "flat";
        if (!isnan(avg) && avg > 0) { float d = (todayMl - avg) / avg * 100.0f; if (d > TREND_PCT) trend = "up"; else if (d < -TREND_PCT) trend = "down"; }
        Serial.print(",\"trend\":\""); Serial.print(trend); Serial.print("\"");
    }
    Serial.println("}");
    todayMl = 0; todayDrinks = 0;
}

void closeSession(float endG, unsigned long now) {
    inSession = false;
    if (isnan(sessionStartG)) return;
    float drop = sessionStartG - endG;
    if (drop >= DRINK_MIN_ML) {
        todayMl += drop; todayDrinks++;
        logEvent("drink " + String(drop, 0) + " ml");
        Serial.print("{\"event\":\"drink\",\"ml\":"); Serial.print(drop, 0);
        Serial.print(",\"secs\":"); Serial.print((now - unstableSince) / 1000);
        Serial.print(",\"today_ml\":"); Serial.print(todayMl, 0); printMlPerKgToday(); Serial.println("}");
    }
    sessionStartG = NAN;
}

void processSample(long raw) {
    sampleCount++;
    if (raw >= 8388607L || raw <= -8388608L) { if (++saturatedCount % 10 == 1) emitError("HX711 saturated: open input or broken cell wire"); return; }
    medBuf[medIdx] = raw; medIdx = (medIdx + 1) % MEDIAN_N; if (medFill < MEDIAN_N) medFill++;
    float g = rawToGrams(medianOf(medBuf, medFill));
    if (!emaInit) { ema = g; emaInit = true; } else ema += EMA_ALPHA * (g - ema);
    stabBuf[stabIdx] = ema; stabIdx = (stabIdx + 1) % STABLE_N; if (stabFill < STABLE_N) stabFill++;
    float lo = stabBuf[0], hi = stabBuf[0];
    for (int i = 1; i < stabFill; i++) { if (stabBuf[i] < lo) lo = stabBuf[i]; if (stabBuf[i] > hi) hi = stabBuf[i]; }
    bool stable = (stabFill == STABLE_N) && (hi - lo) <= STABLE_G;
    unsigned long now = millis();
    if (now - dayStartMs > DAY_MS) { dayStartMs = now; rolloverDay(); }

    // learn the bowl: lowest stable total ever seen that is still a plausible bowl
    if (stable && calibrated && ema >= MIN_BOWL_G && (!bowlKnown || ema < bowlG - 2.0f)) {
        bowlG = ema; bowlKnown = true; savePrefs();
        Serial.print("{\"event\":\"bowl_learned\",\"bowl_g\":"); Serial.print(bowlG, 0); Serial.println("}"); logEvent("bowl learned: " + String(bowlG, 0) + " g");
    }
    float waterMl = bowlKnown ? fmaxf(ema - bowlG, 0.0f) : NAN;

    // drinking sessions: stable -> unstable (dog at the bowl) -> stable lower
    if (!stable) {
        if (!inSession && !isnan(lastStableG)) { inSession = true; sessionStartG = lastStableG; unstableSince = now; }
        lastUnstableMs = now;
    } else {
        if (inSession && now - lastUnstableMs >= DRINK_GAP_MS) closeSession(ema, now);
        lastStableG = ema;
    }

    // state
    State s;
    if (ema < LIFT_G) s = ST_LIFTED;
    else if (inSession) s = ST_DRINKING;
    else if (!bowlKnown) s = ST_OK;
    else if (waterMl <= emptyMl) s = ST_EMPTY;
    else if (waterMl <= lowMl) s = ST_LOW;
    else s = ST_OK;
    state = s;
    // voice: fire once on the way into "empty", re-arm when water is back, stop on lift / refill / timeout
    if (s == ST_EMPTY && voiceArmed && voiceEnabled && !isNight()) { voiceArmed = false; voiceStart("empty"); }
    if (s == ST_OK || s == ST_LOW) voiceArmed = true;
    if (voiceRun && (s != ST_EMPTY || millis() - voiceStartMs > VOICE_MS)) voiceStop();

    static unsigned long lastPrint = 0;
    if (now - lastPrint >= 500) {   // 2 Hz on the wire is plenty for the app
        lastPrint = now;
        Serial.print("{\"g\":"); Serial.print(ema, 1);
        Serial.print(",\"water_ml\":"); if (bowlKnown) Serial.print(waterMl, 0); else Serial.print("null");
        Serial.print(",\"bowl_g\":"); if (bowlKnown) Serial.print(bowlG, 0); else Serial.print("null");
        Serial.print(",\"state\":\""); Serial.print(stateName(s));
        Serial.print("\",\"stable\":"); Serial.print(stable ? 1 : 0);
        Serial.print(",\"cal\":"); Serial.print(calibrated ? 1 : 0); printMlPerKgToday(); Serial.println("}");
        webPush(ema, s, stable, waterMl);
    }
}

// ---- commands ---------------------------------------------------------------------------
void doTare() {
    long avg; if (!hxAverage(20, avg)) { hxPresent = false; emitError("HX711 not responding on port 10"); return; }
    hxPresent = true; tareOffset = avg; bowlKnown = false; bowlG = 0; savePrefs(); resetFilters(); lastStableG = NAN;
    Serial.print("{\"event\":\"tared\",\"offsets\":["); Serial.print(tareOffset); Serial.println("]}"); logEvent("tared");
}
void doCalibrate(float refGrams) {
    if (refGrams < 0.1f || refGrams > 7000.0f) { emitError("CAL grams out of range"); return; }
    long avg; if (!hxAverage(30, avg)) { hxPresent = false; emitError("HX711 not responding"); return; }
    long net = avg - tareOffset; if (labs(net) < 100) { emitError("no load seen: TARE with an empty platter, then put the reference mass on"); return; }
    scaleFactor = (float)net / refGrams; calibrated = true; savePrefs(); resetFilters();
    Serial.print("{\"event\":\"calibrated\",\"ref_g\":"); Serial.print(refGrams, 1); Serial.print(",\"factors\":["); Serial.print(scaleFactor, 2); Serial.println("]}"); logEvent("calibrated with " + String(refGrams, 0) + " g: " + String(scaleFactor, 1) + " counts/g");
}
void printStatus() {
    Serial.print("{\"event\":\"status\",\"calibrated\":"); Serial.print(calibrated ? 1 : 0);
    Serial.print(",\"factor\":"); Serial.print(scaleFactor, 2); Serial.print(",\"offset\":"); Serial.print(tareOffset);
    Serial.print(",\"bowl_g\":"); Serial.print(bowlG, 0); Serial.print(",\"bowl_known\":"); Serial.print(bowlKnown ? 1 : 0);
    Serial.print(",\"low_ml\":"); Serial.print(lowMl, 0); Serial.print(",\"empty_ml\":"); Serial.print(emptyMl, 0);
    Serial.print(",\"today_ml\":"); Serial.print(todayMl, 0); Serial.print(",\"drinks\":"); Serial.print(todayDrinks);
    Serial.print(",\"dog_kg\":"); if (dogKnown()) Serial.print(dogKg, 1); else Serial.print("null"); printMlPerKgToday();
    Serial.print(",\"glow\":"); Serial.print(glowEnabled ? 1 : 0);
    Serial.print(",\"name\":\""); Serial.print(dogName); Serial.print("\",\"ap_ip\":\""); Serial.print(WiFi.softAPIP()); Serial.print("\",\"sta_ip\":\""); Serial.print(WiFi.status() == WL_CONNECTED ? WiFi.localIP().toString() : ""); Serial.print("\"");
    Serial.print(",\"voice\":"); Serial.print(voiceEnabled ? 1 : 0); Serial.print(",\"volume\":"); Serial.print(volumePct); Serial.print(",\"speaking\":"); Serial.print(voiceRun ? 1 : 0);
    Serial.print(",\"ambient\":"); Serial.print(ambientPct); Serial.print(",\"night\":"); Serial.print(isNight() ? 1 : 0);
    Serial.print(",\"night_on\":"); Serial.print(nightOn); Serial.print(",\"night_off\":"); Serial.print(nightOff);
    Serial.print(",\"clock\":"); if (clockKnown) { int m = clockNowMin(); char buf[8]; snprintf(buf, sizeof(buf), "\"%02d:%02d\"", m / 60, m % 60); Serial.print(buf); } else Serial.print("null");
    Serial.print(",\"grids\":"); Serial.print(gridCount());
    Serial.print(",\"hx711_present\":"); Serial.print(hxPresent ? 1 : 0); Serial.print(",\"samples\":"); Serial.print(sampleCount);
    Serial.println(",\"fw\":\"" FW_VERSION "\"}");
}
String cmdBuf;
void handleCommand(String line) {
    line.trim(); if (!line.length()) return; String up = line; up.toUpperCase();
    if (up == "TARE") doTare();
    else if (up.startsWith("CAL ")) doCalibrate(line.substring(4).toFloat());
    else if (up.startsWith("FACTOR ")) { float f = line.substring(7).toFloat(); if (fabsf(f) < 1) { emitError("FACTOR >= 1"); return; } scaleFactor = f; calibrated = true; savePrefs(); resetFilters(); printStatus(); }
    else if (up.startsWith("BOWL ")) { bowlG = line.substring(5).toFloat(); bowlKnown = bowlG >= MIN_BOWL_G; savePrefs(); logEvent(bowlKnown ? "bowl set: " + String(bowlG, 0) + " g" : "bowl forgotten"); printStatus(); }
    else if (up.startsWith("LEVELS ")) { int sp = line.indexOf(' ', 7); if (sp < 0) { emitError("LEVELS <low_ml> <empty_ml>"); return; } lowMl = line.substring(7, sp).toFloat(); emptyMl = line.substring(sp + 1).toFloat(); savePrefs(); printStatus(); }
    else if (up.startsWith("GLOW ")) { glowEnabled = line.substring(5).toInt() != 0; savePrefs(); printStatus(); }
    else if (up.startsWith("DOG ")) { float kg = line.substring(4).toFloat(); if (kg < DOG_KG_MIN || kg > DOG_KG_MAX) { emitError("DOG <kg> 0.5..100"); return; } dogKg = kg; savePrefs(); printStatus(); }
    else if (up.startsWith("AMBIENT ")) { int p = line.substring(8).toInt(); if (p < 0 || p > 100) { emitError("AMBIENT <pct> 0..100"); return; } ambientPct = (uint8_t)p; savePrefs(); printStatus(); }
    else if (up.startsWith("NIGHT ")) {
        int sp = line.indexOf(' ', 6); if (sp < 0) { emitError("NIGHT <on_hour> <off_hour> (24 h; same hour = off)"); return; }
        int on = line.substring(6, sp).toInt(), off = line.substring(sp + 1).toInt();
        if (on < 0 || on > 23 || off < 0 || off > 23) { emitError("NIGHT hours 0..23"); return; }
        nightOn = (uint8_t)on; nightOff = (uint8_t)off; savePrefs(); printStatus();
    }
    else if (up.startsWith("TIME ")) {
        int colon = line.indexOf(':', 5); if (colon < 0) { emitError("TIME <hh:mm>"); return; }
        int hh = line.substring(5, colon).toInt(), mm = line.substring(colon + 1).toInt();
        if (hh < 0 || hh > 23 || mm < 0 || mm > 59) { emitError("TIME hh 0..23, mm 0..59"); return; }
        clockMin = (uint16_t)(hh * 60 + mm); clockSetMs = millis(); clockKnown = true; printStatus();
    }
    else if (up.startsWith("VOICE ")) { voiceEnabled = line.substring(6).toInt() != 0; if (!voiceEnabled) voiceStop(); savePrefs(); printStatus(); }
    else if (up.startsWith("VOLUME ")) { int p = line.substring(7).toInt(); if (p < 0 || p > 100) { emitError("VOLUME <pct> 0..100"); return; } volumePct = (uint8_t)p; speaker.setVolume(volumePct / 100.0f); savePrefs(); printStatus(); }
    else if (up == "SAY") { voiceArmed = false; voiceStart("say"); voiceStartMs = millis() - (VOICE_MS - 2 * (VOICE_N * 1000UL / VOICE_RATE + VOICE_GAP_MS)); }   // test: two repetitions then stop
    else if (up.startsWith("NAME ")) { dogName = line.substring(5); dogName.trim(); savePrefs(); printStatus(); }
    else if (up.startsWith("WIFI ")) { int sp = line.indexOf(' ', 5); staSsid = sp < 0 ? line.substring(5) : line.substring(5, sp); staPass = sp < 0 ? "" : line.substring(sp + 1); savePrefs(); WiFi.begin(staSsid.c_str(), staPass.c_str()); printStatus(); }
    else if (up == "HISTORY") printHistory();
    else if (up == "STATUS") printStatus();
    else if (up == "HELP" || up == "?") Serial.println("{\"event\":\"help\",\"commands\":[\"TARE\",\"CAL <g>\",\"FACTOR <cpg>\",\"BOWL <g>\",\"LEVELS <low_ml> <empty_ml>\",\"GLOW 0|1\",\"AMBIENT <pct>\",\"NIGHT <on_hour> <off_hour>\",\"TIME <hh:mm>\",\"DOG <kg>\",\"VOICE 0|1\",\"VOLUME <pct>\",\"SAY\",\"NAME <dog>\",\"WIFI <ssid> <pass>\",\"HISTORY\",\"STATUS\"]}");
    else emitError("unknown command");
}

// ---- web server ---------------------------------------------------------------------------
void webSendData() {
    String j; j.reserve(6000);
    j += "{\"now\":" + String(millis()) + ",\"fw\":\"" FW_VERSION "\",\"name\":\"" + dogName + "\"";
    j += ",\"calibrated\":" + String(calibrated ? 1 : 0) + ",\"voice\":" + String(voiceEnabled ? 1 : 0) + ",\"volume\":" + String(volumePct);
    j += ",\"today_ml\":" + String(todayMl, 0) + ",\"drinks\":" + String(todayDrinks);
    j += ",\"water_ml\":" + (bowlKnown && !isnan(webWaterMl) ? String(webWaterMl, 0) : String("null"));
    j += ",\"bowl_g\":" + (bowlKnown ? String(bowlG, 0) : String("null"));
    j += ",\"stations\":" + String(WiFi.softAPgetStationNum());
    j += ",\"sta_ip\":" + (WiFi.status() == WL_CONNECTED ? "\"" + WiFi.localIP().toString() + "\"" : String("null"));
    j += ",\"samples\":[";
    for (int i = 0; i < webFill; i++) {
        const WebSample &w = webBuf[(webIdx - webFill + i + WEB_N) % WEB_N];
        if (i) j += ",";
        j += "[" + String(w.t) + "," + String(w.g, 1) + ",\"" + stateName((State)w.st) + "\"," + String(w.stable) + "]";
    }
    j += "],\"events\":[";
    for (int i = 0; i < webEvFill; i++) { if (i) j += ","; String e = webEvents[(webEvIdx - webEvFill + i + 16) % 16]; e.replace("\"", "'"); j += "\"" + e + "\""; }
    j += "]}";
    web.sendHeader("Cache-Control", "no-store"); web.send(200, "application/json", j);
}
void webBegin() {
    String ssid = dogName.length() ? dogName : String("Lapper");     // the WiFi is just the dog's name
    WiFi.mode(WIFI_AP_STA); WiFi.softAP(ssid.c_str());             // open network, captive portal
    if (staSsid.length()) WiFi.begin(staSsid.c_str(), staPass.c_str());
    dns.start(53, "*", WiFi.softAPIP());
    web.on("/", []() { web.sendHeader("Cache-Control", "no-store"); web.send_P(200, "text/html", LAPPER_PAGE); });
    web.on("/data", webSendData);
    web.on("/cmd", []() { String c = web.arg("c"); c.trim(); String u = c; u.toUpperCase();
        bool ok = c.length() && (u == "TARE" || u.startsWith("CAL ") || u == "SAY" || u.startsWith("VOICE ") || u.startsWith("VOLUME ") || u.startsWith("DOG ") || u.startsWith("NAME ") || u.startsWith("LEVELS ") || u.startsWith("BOWL ") || u == "STATUS");
        if (ok) handleCommand(c);
        web.send(200, "application/json", String("{\"sent\":") + (ok ? "true" : "false") + "}"); });
    web.on("/wifi", []() { staSsid = web.arg("ssid"); staPass = web.arg("pass"); savePrefs(); WiFi.begin(staSsid.c_str(), staPass.c_str()); web.send(200, "application/json", "{\"joining\":true}"); });
    web.onNotFound([]() { web.sendHeader("Location", "http://" + WiFi.softAPIP().toString() + "/", true); web.send(302, "text/plain", ""); });   // captive-portal probes (Apple, Android, Windows) land on the page
    web.begin(); webUp = true;
    Serial.print("{\"event\":\"wifi\",\"ap\":\""); Serial.print(ssid); Serial.print("\",\"ip\":\""); Serial.print(WiFi.softAPIP()); Serial.println("\"}");
}
void webLoop() { if (!webUp) return; dns.processNextRequest(); web.handleClient();
    static bool wasUp = false; bool up = WiFi.status() == WL_CONNECTED;
    if (up != wasUp) { wasUp = up; if (up) { logEvent("home wifi: " + WiFi.localIP().toString()); Serial.print("{\"event\":\"wifi\",\"sta_ip\":\""); Serial.print(WiFi.localIP()); Serial.println("\"}"); } } }

void setup() {
    pinMode(HX_PORT_SCK, OUTPUT); pinMode(HX_PORT_DOUT, INPUT); digitalWrite(HX_PORT_SCK, LOW);
    for (int i = 0; i < 4; i++) {
        if (ONBOARD_A[i] < 0 && ONBOARD_B[i] < 0) continue;
        onboardPorts++;
        if (ONBOARD_A[i] >= 0) { onboardW[onboardN] = false; onboard[onboardN++] = new Adafruit_NeoPixel(GRID_PX, ONBOARD_A[i], NEO_GRB + NEO_KHZ800); }
        if (ONBOARD_B[i] >= 0) { onboardW[onboardN] = true;  onboard[onboardN++] = new Adafruit_NeoPixel(GRID_PX, ONBOARD_B[i], NEO_GRBW + NEO_KHZ800); }
    }
    ledA.begin(); ledA.setBrightness(BRIGHT_CAP); ledB.begin(); ledB.setBrightness(BRIGHT_CAP);
    for (int s = 0; s < onboardN; s++) { onboard[s]->begin(); onboard[s]->setBrightness(BRIGHT_CAP); }   // the cap, once, on every strip
    setAll(0, 0, 0);
    delay(2000); Serial.begin(115200);
    loadPrefs(); speaker.begin(VOICE_RATE); speaker.setVolume(volumePct / 100.0f); webBegin(); dayStartMs = millis();
    long dummy; for (int i = 0; i < 3; i++) hxReadBlocking(dummy, 300);
    // auto-tare at power-up: if the platter carries less than a bowl, this is the new zero.
    // With a bowl on it (a power blip mid-session) the stored tare is kept, otherwise the bowl would read as nothing.
    { long avg; if (hxAverage(10, avg)) {
        float g = (avg - tareOffset) / scaleFactor;
        if (fabsf(g) < MIN_BOWL_G) { tareOffset = avg; savePrefs(); resetFilters(); lastStableG = NAN;
            Serial.print("{\"event\":\"auto_tared\",\"was_g\":"); Serial.print(g, 1); Serial.println("}"); logEvent("auto-tared at power-up"); }
        else { const char *why = g > 0 ? "bowl on platter" : "lighter than the stored zero (platter off?)";
            Serial.print("{\"event\":\"auto_tare_skipped\",\"g\":"); Serial.print(g, 1); Serial.print(",\"reason\":\""); Serial.print(why); Serial.println("\"}");
            logEvent(String("auto-tare skipped: ") + why); }
    } }
    Serial.print("{\"event\":\"boot\",\"calibrated\":"); Serial.print(calibrated ? 1 : 0);
    Serial.print(",\"bowl_known\":"); Serial.print(bowlKnown ? 1 : 0);
    Serial.print(",\"grids\":"); Serial.print(gridCount()); Serial.println(",\"fw\":\"" FW_VERSION "\"}");
}
void loop() {
    webLoop();
    while (Serial.available()) { char c = Serial.read(); if (c == '\n') { handleCommand(cmdBuf); cmdBuf = ""; } else if (c != '\r' && cmdBuf.length() < 64) cmdBuf += c; }
    if (hxReady()) { processSample(hxReadRaw()); lastReady = millis(); hxPresent = true; }
    else if (millis() - lastReady > HX_TIMEOUT_MS && hxPresent) { hxPresent = false; emitError("HX711 not responding (DOUT stuck high): check port 10"); }
    glowUpdate();
}
