/**
 * ENEO asset tag firmware
 *
 * Non-connectable BLE advertiser. Broadcasts the device name on a fixed
 * 1-second interval. The tag's BLE MAC address is its identity — gateways
 * record (mac, rssi) per advertisement and the server resolves location.
 */

#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/bluetooth/bluetooth.h>

LOG_MODULE_REGISTER(tag, CONFIG_LOG_DEFAULT_LEVEL);

/* Adv interval in 0.625 ms units. 0x0320 = 500 ms (2 Hz).
 * Doubled from 0x0640 (1000 ms) to roughly double per-scan catch rate
 * on the gateway side. Trade: tag battery life ~3.5 yr → ~1.8 yr on CR2450,
 * which is fine for hospital ops with annual battery swaps.
 */
#define ADV_INTERVAL_UNITS 0x0320

#define DEVICE_NAME      CONFIG_BT_DEVICE_NAME
#define DEVICE_NAME_LEN  (sizeof(DEVICE_NAME) - 1)

/* Manufacturer-specific data attached to every advertisement.
 * Layout: [company_id_lo, company_id_hi, format_version, battery_pct]
 *
 * Company ID 0xFFFF is the BT SIG-reserved test/internal value — fine
 * for development. Replace with an assigned company ID before shipping.
 *
 * battery_pct is currently a hardcoded placeholder (100). To wire up a
 * real reading: sample VBAT via SAADC (the Feather routes LiPo through a
 * 100k/100k divider to A6 / P0.05), convert to a percentage, write it to
 * mfg_data[3], and call bt_le_adv_update_data() periodically.
 */
static uint8_t mfg_data[] = {
	0xFF, 0xFF,   /* company ID 0xFFFF (test/internal) */
	0x01,         /* format version */
	100,          /* battery percent — placeholder, replace with ADC */
};

static const struct bt_data ad[] = {
	BT_DATA_BYTES(BT_DATA_FLAGS, BT_LE_AD_NO_BREDR),
	BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
	BT_DATA(BT_DATA_MANUFACTURER_DATA, mfg_data, sizeof(mfg_data)),
};

int main(void)
{
	int err;
	bt_addr_le_t addr;
	char addr_str[BT_ADDR_LE_STR_LEN];

	LOG_INF("ENEO tag starting");

	err = bt_enable(NULL);
	if (err) {
		LOG_ERR("Bluetooth init failed (%d)", err);
		return err;
	}

	size_t count = 1;
	bt_id_get(&addr, &count);
	bt_addr_le_to_str(&addr, addr_str, sizeof(addr_str));
	LOG_INF("Tag identity: %s", addr_str);

	struct bt_le_adv_param adv_param = {
		.id = BT_ID_DEFAULT,
		.sid = 0,
		.secondary_max_skip = 0,
		.options = BT_LE_ADV_OPT_USE_IDENTITY,
		.interval_min = ADV_INTERVAL_UNITS,
		.interval_max = ADV_INTERVAL_UNITS,
		.peer = NULL,
	};

	err = bt_le_adv_start(&adv_param, ad, ARRAY_SIZE(ad), NULL, 0);
	if (err) {
		LOG_ERR("Advertising failed to start (%d)", err);
		return err;
	}

	LOG_INF("Advertising started, interval ~500 ms");

	/* main can return; Zephyr's idle thread sleeps the MCU between adv events */
	return 0;
}
