/*
 * BeeGuardian AI — ESP32 Firmware
 * ---------------------------------------------------------------
 * Reads BME280 (temperature/humidity), HX711 (weight) and INMP441 (audio),
 * runs on-device Edge Impulse classifier, fuses sensors into a Hive
 * Health Score, publishes JSON telemetry over MQTT to HiveMQ, and
 * accepts remote commands. Designed for solar + 18650 with deep sleep.
 *
 * Board:    ESP32 DevKit V1
 * IDE:      Arduino IDE 2.x
 * Libs:     WiFi, PubSubClient, Adafruit BME280, HX711, ArduinoJson,
 *           beeguardian-inferencing (Edge Impulse export)
 * ---------------------------------------------------------------
 */

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <HX711.h>
#include <ArduinoJson.h>
#include <driver/i2s.h>
#include <beeguardian-inferencing.h>

// ---------- CONFIG ----------
#define WIFI_SSID       "YOUR_WIFI"
#define WIFI_PASS       "YOUR_PASS"
#define MQTT_HOST       "broker.hivemq.com"
#define MQTT_PORT       1883
#define HIVE_ID         "hive-01"
#define TOPIC_STATE     "beeguardian/" HIVE_ID "/state"
#define TOPIC_ALERT     "beeguardian/" HIVE_ID "/alert"
#define TOPIC_CMD       "beeguardian/" HIVE_ID "/cmd/#"
#define SLEEP_SECONDS   30

// ---------- PINS ----------
#define HX711_DOUT      16
#define HX711_SCK       4
#define I2S_WS          25
#define I2S_SD          33
#define I2S_SCK         32

// ---------- GLOBALS ----------
WiFiClient wifi;
PubSubClient mqtt(wifi);
Adafruit_BME280 bme;
HX711 scale;
RTC_DATA_ATTR int bootCount = 0;

// ---------- SENSOR READS ----------
float readTemperatureC()   { return bme.readTemperature(); }
float readHumidityPct()    { return bme.readHumidity(); }
float readWeightKg()       { return scale.get_units(10) / 1000.0f; }

// ---------- AUDIO CAPTURE ----------
static int16_t audio_buffer[EI_CLASSIFIER_RAW_SAMPLE_COUNT];

bool captureAudio() {
  size_t bytes_read;
  return i2s_read(I2S_NUM_0, audio_buffer,
                  sizeof(audio_buffer), &bytes_read, portMAX_DELAY) == ESP_OK;
}

int audio_get_data(size_t offset, size_t length, float *out) {
  for (size_t i = 0; i < length; i++) out[i] = audio_buffer[offset + i] / 32768.0f;
  return 0;
}

struct Classification { float normal, stress, noise; };

Classification runInference() {
  signal_t signal;
  signal.total_length = EI_CLASSIFIER_RAW_SAMPLE_COUNT;
  signal.get_data     = &audio_get_data;
  ei_impulse_result_t result;
  run_classifier(&signal, &result, false);
  Classification c = {0, 0, 0};
  for (size_t i = 0; i < EI_CLASSIFIER_LABEL_COUNT; i++) {
    String lbl = String(result.classification[i].label);
    float  v   = result.classification[i].value;
    if      (lbl == "normal") c.normal = v;
    else if (lbl == "stress") c.stress = v;
    else                      c.noise  = v;
  }
  return c;
}

// ---------- SENSOR FUSION ----------
int computeHealthScore(float t, float h, float w, float normalConf) {
  float tScore = 100.0f - min(100.0f, fabsf(t - 35.0f)  * 18.0f);
  float hScore = 100.0f - min(100.0f, fabsf(h - 57.5f) *  3.0f);
  float wScore = constrain((w - 20.0f) * 4.0f, 0.0f, 100.0f);
  float aScore = normalConf * 100.0f;
  int   s = (int)(tScore * 0.25f + hScore * 0.20f + wScore * 0.20f + aScore * 0.35f);
  return constrain(s, 0, 100);
}

// ---------- MQTT ----------
void onCmd(char* topic, byte* payload, unsigned int len) {
  String t(topic); String p; for (unsigned i = 0; i < len; i++) p += (char)payload[i];
  Serial.printf("[CMD] %s => %s\n", t.c_str(), p.c_str());
  if (t.endsWith("/reboot"))    ESP.restart();
  if (t.endsWith("/calibrate")) { scale.tare(); }
}

void ensureMqtt() {
  while (!mqtt.connected()) {
    if (mqtt.connect(HIVE_ID)) {
      mqtt.subscribe(TOPIC_CMD);
      Serial.println("[MQTT] connected");
    } else { delay(1500); }
  }
}

// ---------- PUBLISH ----------
void publishState(float t, float h, float w, Classification c, int score) {
  StaticJsonDocument<384> doc;
  doc["hive_id"]     = HIVE_ID;
  doc["ts"]          = millis();
  doc["temperature"] = t;
  doc["humidity"]    = h;
  doc["weight"]      = w;
  JsonObject audio   = doc.createNestedObject("audio");
  audio["normal"]    = c.normal;
  audio["stress"]    = c.stress;
  audio["noise"]     = c.noise;
  const char* label  = c.stress > 0.5 ? "Stress" : c.normal > 0.6 ? "Normal" : "Unknown";
  doc["classification"] = label;
  doc["confidence"]     = max(c.normal, max(c.stress, c.noise));
  doc["score"]          = score;
  doc["status"]         = score >= 75 ? "healthy" : score >= 50 ? "warning" : "critical";
  char buf[512]; size_t n = serializeJson(doc, buf);
  mqtt.publish(TOPIC_STATE, buf, n);

  if (score < 50 || c.stress > 0.5 || t > 38) {
    StaticJsonDocument<192> a;
    a["hive_id"] = HIVE_ID; a["ts"] = millis();
    a["level"]   = score < 40 ? "critical" : "warning";
    a["reason"]  = c.stress > 0.5 ? "stress_buzz" : t > 38 ? "high_temp" : "low_score";
    char abuf[256]; size_t an = serializeJson(a, abuf);
    mqtt.publish(TOPIC_ALERT, abuf, an);
  }
}

// ---------- SETUP / LOOP ----------
void setup() {
  Serial.begin(115200);
  bootCount++;
  Wire.begin();
  bme.begin(0x76);
  scale.begin(HX711_DOUT, HX711_SCK);
  scale.set_scale(420.f); // TODO calibrate

  i2s_config_t cfg = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = EI_CLASSIFIER_FREQUENCY,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = I2S_COMM_FORMAT_STAND_I2S,
    .intr_alloc_flags = 0, .dma_buf_count = 4, .dma_buf_len = 1024,
    .use_apll = false, .tx_desc_auto_clear = false, .fixed_mclk = 0
  };
  i2s_pin_config_t pins = { I2S_SCK, I2S_WS, I2S_PIN_NO_CHANGE, I2S_SD };
  i2s_driver_install(I2S_NUM_0, &cfg, 0, NULL);
  i2s_set_pin(I2S_NUM_0, &pins);

  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) { delay(200); }
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
  mqtt.setCallback(onCmd);
  ensureMqtt();

  float t = readTemperatureC();
  float h = readHumidityPct();
  float w = readWeightKg();
  captureAudio();
  Classification c = runInference();
  int score = computeHealthScore(t, h, w, c.normal);
  publishState(t, h, w, c, score);
  mqtt.loop(); delay(200);

  Serial.printf("[SLEEP] %ds\n", SLEEP_SECONDS);
  esp_sleep_enable_timer_wakeup((uint64_t)SLEEP_SECONDS * 1000000ULL);
  esp_deep_sleep_start();
}

void loop() { /* never reached — deep sleep */ }
