"""
Energy cost of *useful* data in a LoRaWAN sensor node:
does on-node event filtering (TinyML) + payload-aware adaptive spreading
factor beat sending every sample?

A reproducible simulation experiment.
--------------------------------------------------------------
Scope: this is a MODEL-BASED experiment, not a hardware measurement.
Every physical constant below is taken from a public datasheet or from the
literature reviewed in the accompanying article; every random draw is seeded,
so the numbers in results/summary.json can be regenerated exactly.

Physics / energy model
  * LoRa airtime: Semtech application note AN1200.13, packet time-on-air
    formula for BW = 125 kHz, CR = 4/5, 8-symbol preamble, explicit header,
    payload CRC on.
  * Radio currents (SX1276 @ 17 dBm, 3.3 V): I_TX = 120 mA, I_sleep = 1.5 uA.
  * Per-transmission fixed overhead (MCU wake, radio switch, two RX windows):
    150 ms at 7 mA.
  * Sampling: 20 ms at 5 mA per 60 s sample.
  * TinyML inference: 12 ms at 8 mA per sample.
  * Link: margin above the demodulation floor of the chosen SF, with 6 dB
    log-normal shadowing per transmission; required SNR improves ~2.5 dB per
    SF step. Packet error rate = exp(-0.5 * 10^(margin_dB/10)).
  * Battery: 2 x AA, 2500 mAh at 3.3 V = 29,700 J.

Policies
  A always_fixed      : transmit every sample at SF7  (baseline)
  B always_adaptive   : transmit every sample, pick lowest SF that clears a
                        10 dB margin using a noisy SNR estimate
  C filter_fixed      : TinyML gate, transmit only flagged samples at SF7
  D filter_adaptive   : TinyML gate + adaptive SF  (the proposed combination)
"""

import json
import math
import os
from dataclasses import asdict, dataclass

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "results")
os.makedirs(OUT, exist_ok=True)

# ---------------------------------------------------------------- constants
V_SUPPLY = 3.3
I_TX = 0.120              # A
I_SLEEP = 1.5e-6          # A
E_OVERHEAD = 0.150 * 0.007 * V_SUPPLY      # J per transmission
E_SAMPLE = 0.020 * 0.005 * V_SUPPLY        # J per sample
E_INFER = 0.012 * 0.008 * V_SUPPLY         # J per TinyML inference
BATTERY_J = 2500e-3 * 3600 * V_SUPPLY      # J

SAMPLE_PERIOD_S = 60
DAYS = 7
N_SAMPLES = DAYS * 24 * 60
ANOMALY_P = 0.02           # 2 % of samples are events worth reporting
SE = 0.95                  # TinyML sensitivity  (catches 95 % of events)
PAYLOAD_BYTES = 20

TARGET_MARGIN_DB = 10.0    # adaptive policy aims for <=~1 % PER
SF_STEP_DB = 2.5
SHADOW_SIGMA_DB = 6.0
EST_SIGMA_DB = 2.5         # noise in the node's own SNR estimate

POLICIES = ["always_fixed", "always_adaptive", "filter_fixed", "filter_adaptive"]
LABELS = {
    "always_fixed": "A. Send all, fixed SF7",
    "always_adaptive": "B. Send all, adaptive SF",
    "filter_fixed": "C. TinyML filter, fixed SF7",
    "filter_adaptive": "D. TinyML filter + adaptive SF",
}
COLORS = {
    "always_fixed": "#94a3b8",
    "always_adaptive": "#6366f1",
    "filter_fixed": "#f59e0b",
    "filter_adaptive": "#0f766e",
}


@dataclass
class Run:
    policy: str
    margin0_db: float
    false_alarm_rate: float
    energy_j: float
    correct_delivered: int
    total_anomalies: int
    false_alarms_delivered: int
    transmissions: int
    mean_airtime_s: float
    recall: float
    energy_per_event_j: float
    battery_life_years: float
    latency_s: float


def airtime_batch(payload, sf, bw=125_000.0, cr=1, preamble=8, crc=1, ih=0):
    """Semtech AN1200.13 time-on-air (seconds), vectorised over SF."""
    sf = np.asarray(sf, dtype=float)
    tsym = (2.0 ** sf) / bw
    t_preamble = (preamble + 4.25) * tsym
    de = np.where(sf >= 11, 1.0, 0.0)          # low-data-rate optimisation
    num = 8.0 * payload - 4.0 * sf + 28.0 + 16.0 * crc - 20.0 * ih
    den = 4.0 * (sf - 2.0 * de)
    symbols = 8.0 + np.maximum(np.ceil(num / den) * (cr + 4), 0.0)
    return t_preamble + symbols * tsym


def simulate(policy, margin0_db, false_alarm_rate, seed):
    rng = np.random.default_rng(seed)
    is_event = rng.random(N_SAMPLES) < ANOMALY_P
    total_events = int(is_event.sum())

    filtered = policy in ("filter_fixed", "filter_adaptive")
    adaptive = policy in ("always_adaptive", "filter_adaptive")

    if filtered:
        hit = is_event & (rng.random(N_SAMPLES) < SE)
        false_pos = (~is_event) & (rng.random(N_SAMPLES) < false_alarm_rate)
        transmit = hit | false_pos
    else:
        transmit = np.ones(N_SAMPLES, dtype=bool)

    idx = np.flatnonzero(transmit)
    m = idx.size

    energy = E_SAMPLE * N_SAMPLES
    if filtered:
        energy += E_INFER * N_SAMPLES

    if m:
        if adaptive:
            est = margin0_db + rng.normal(0.0, EST_SIGMA_DB, m)
            raw = np.ceil(7.0 + (TARGET_MARGIN_DB - est) / SF_STEP_DB)
            sf = np.clip(raw, 7, 12)
        else:
            sf = np.full(m, 7.0)

        true_margin = margin0_db + SF_STEP_DB * (sf - 7.0) + rng.normal(0.0, SHADOW_SIGMA_DB, m)
        per = np.clip(np.exp(-0.5 * 10.0 ** (true_margin / 10.0)), 0.0, 1.0)
        delivered = rng.random(m) >= per

        air = airtime_batch(PAYLOAD_BYTES, sf)
        energy += float(np.sum(air * V_SUPPLY * (I_TX - I_SLEEP)))
        energy += E_OVERHEAD * m
        mean_air = float(np.mean(air))
        n_tx = m
        delivered_events = int(np.sum(delivered & is_event[idx]))
        fa_delivered = int(np.sum(delivered & ~is_event[idx]))
    else:                                    # pragma: no cover
        mean_air, n_tx, delivered_events, fa_delivered = 0.0, 0, 0, 0

    recall = delivered_events / total_events if total_events else 0.0
    per_event = energy / delivered_events if delivered_events else float("inf")
    return Run(
        policy=policy,
        margin0_db=margin0_db,
        false_alarm_rate=false_alarm_rate,
        energy_j=energy,
        correct_delivered=delivered_events,
        total_anomalies=total_events,
        false_alarms_delivered=fa_delivered,
        transmissions=n_tx,
        mean_airtime_s=mean_air,
        recall=recall,
        energy_per_event_j=per_event,
        # energy is accumulated over DAYS days, so scale to a year
        battery_life_years=BATTERY_J / energy * (DAYS / 365.25),
        latency_s=mean_air + SAMPLE_PERIOD_S / 2.0,
    )


def aggregate(runs):
    keys = ["energy_j", "recall", "energy_per_event_j", "battery_life_years",
            "transmissions", "false_alarms_delivered", "latency_s"]
    out = {}
    for k in keys:
        vals = np.array([getattr(r, k) for r in runs], dtype=float)
        out[k] = float(np.mean(vals))
        out[k + "_ci95"] = float(1.96 * np.std(vals, ddof=1) / math.sqrt(len(vals)))
    return out


def main():
    reps = 30
    margins = [0, 2, 4, 6, 8, 10]
    far_levels = [0.001, 0.01, 0.05]

    grid = []          # margin sweep at nominal false-alarm rate
    far_sweep = []     # false-alarm sensitivity at 4 dB margin
    for margin in margins:
        for policy in POLICIES:
            runs = [simulate(policy, margin, 0.01, 1000 * i + margin * 17 + j)
                    for j, i in enumerate(range(reps))]
            row = {"policy": policy, "margin0_db": margin, **aggregate(runs)}
            grid.append(row)
    for far in far_levels:
        for policy in POLICIES:
            runs = [simulate(policy, 4, far, 7000 * k + int(far * 1e5) + j)
                    for j, k in enumerate(range(reps))]
            far_sweep.append({"policy": policy, "false_alarm_rate": far,
                              "margin0_db": 4, **aggregate(runs)})

    # ---- derived comparison: saving of D relative to A, per margin
    savings = []
    for margin in margins:
        a = next(r for r in grid if r["policy"] == "always_fixed" and r["margin0_db"] == margin)
        d = next(r for r in grid if r["policy"] == "filter_adaptive" and r["margin0_db"] == margin)
        c = next(r for r in grid if r["policy"] == "filter_fixed" and r["margin0_db"] == margin)
        savings.append({
            "margin0_db": margin,
            "energy_per_event_A_j": a["energy_per_event_j"],
            "energy_per_event_C_j": c["energy_per_event_j"],
            "energy_per_event_D_j": d["energy_per_event_j"],
            "D_reduction_vs_A_pct": 100 * (1 - d["energy_per_event_j"] / a["energy_per_event_j"]),
            "D_reduction_vs_C_pct": 100 * (1 - d["energy_per_event_j"] / c["energy_per_event_j"]),
            "recall_A": a["recall"], "recall_C": c["recall"], "recall_D": d["recall"],
            "life_A_y": a["battery_life_years"], "life_D_y": d["battery_life_years"],
        })

    payload = {
        "assumptions": {
            "supply_v": V_SUPPLY, "i_tx_a": I_TX, "payload_bytes": PAYLOAD_BYTES,
            "sample_period_s": SAMPLE_PERIOD_S, "days": DAYS,
            "anomaly_probability": ANOMALY_P, "tinyml_sensitivity": SE,
            "nominal_false_alarm_rate": 0.01, "target_margin_db": TARGET_MARGIN_DB,
            "shadowing_sigma_db": SHADOW_SIGMA_DB, "estimate_sigma_db": EST_SIGMA_DB,
            "battery_j": BATTERY_J, "repetitions": reps,
        },
        "margin_sweep": grid,
        "false_alarm_sweep": far_sweep,
        "comparison": savings,
    }
    with open(os.path.join(OUT, "summary.json"), "w") as f:
        json.dump(payload, f, indent=2)

    # ------------------------------------------------------------ figures
    plt.rcParams.update({"font.size": 10, "axes.spines.top": False,
                         "axes.spines.right": False, "figure.dpi": 200})

    # Fig 1: energy per delivered event vs link margin
    fig, ax = plt.subplots(figsize=(7.2, 4.4))
    for p in POLICIES:
        rows = [r for r in grid if r["policy"] == p]
        xs = [r["margin0_db"] for r in rows]
        ys = [r["energy_per_event_j"] for r in rows]
        err = [r["energy_per_event_j_ci95"] for r in rows]
        ax.errorbar(xs, ys, yerr=err, marker="o", ms=4, lw=2,
                    color=COLORS[p], label=LABELS[p], capsize=2.5)
    ax.set_yscale("log")
    ax.set_xlabel("Link margin above SF7 demodulation floor (dB)")
    ax.set_ylabel("Energy per correctly delivered event (J, log)")
    ax.set_title("Energy cost of useful data vs link quality (7-day runs, 95 % CI)")
    ax.grid(alpha=0.25, which="both", lw=0.5)
    ax.legend(fontsize=8, frameon=False)
    fig.tight_layout()
    fig.savefig(os.path.join(OUT, "fig1_energy_per_event.png"))
    plt.close(fig)

    # Fig 2: recall and false alarms
    fig, axes = plt.subplots(1, 2, figsize=(8.4, 3.8))
    for p in POLICIES:
        rows = [r for r in grid if r["policy"] == p]
        xs = [r["margin0_db"] for r in rows]
        axes[0].plot(xs, [100 * r["recall"] for r in rows], marker="o", ms=3.5,
                     lw=2, color=COLORS[p], label=LABELS[p])
        axes[1].plot(xs, [r["false_alarms_delivered"] for r in rows], marker="o",
                     ms=3.5, lw=2, color=COLORS[p])
    axes[0].set_xlabel("Link margin (dB)"); axes[0].set_ylabel("Events delivered (%)")
    axes[0].set_title("Coverage: did the event reach the gateway?"); axes[0].grid(alpha=0.25)
    axes[1].set_xlabel("Link margin (dB)"); axes[1].set_ylabel("False alarms delivered / week")
    axes[1].set_title("Price of filtering: false positives"); axes[1].grid(alpha=0.25)
    axes[0].legend(fontsize=7, frameon=False)
    fig.tight_layout()
    fig.savefig(os.path.join(OUT, "fig2_coverage_and_false_alarms.png"))
    plt.close(fig)

    # Fig 3: false-alarm sensitivity at 4 dB margin
    fig, ax = plt.subplots(figsize=(9.0, 4.2))
    width = 0.2
    xs = np.arange(len(far_levels))
    for k, p in enumerate(POLICIES):
        rows = [r for r in far_sweep if r["policy"] == p]
        ys = [r["energy_per_event_j"] for r in rows]
        err = [r["energy_per_event_j_ci95"] for r in rows]
        ax.bar(xs + (k - 1.5) * width, ys, width, yerr=err, capsize=2.5,
               color=COLORS[p], label=LABELS[p])
    ax.set_yscale("log")
    ax.set_xticks(xs); ax.set_xticklabels([f"{f:g}" for f in far_levels])
    ax.set_xlabel("TinyML false-alarm rate on normal samples")
    ax.set_ylabel("Energy per delivered event (J, log)")
    ax.set_title("False alarms cost energy but add almost no coverage (4 dB link margin)")
    ax.grid(alpha=0.25, axis="y", which="both", lw=0.5)
    ax.legend(fontsize=8, frameon=False, loc="center left", bbox_to_anchor=(1.01, 0.5))
    fig.tight_layout()
    fig.savefig(os.path.join(OUT, "fig3_false_alarm_sensitivity.png"))
    plt.close(fig)

    # Fig 4: projected battery life
    fig, ax = plt.subplots(figsize=(7.2, 4.2))
    for p in POLICIES:
        rows = [r for r in grid if r["policy"] == p]
        ax.plot([r["margin0_db"] for r in rows],
                [r["battery_life_years"] for r in rows],
                marker="o", ms=4, lw=2, color=COLORS[p], label=LABELS[p])
    ax.set_yscale("log")
    ax.set_xlabel("Link margin (dB)")
    ax.set_ylabel("Projected life on 2 x AA (years, log)")
    ax.set_title("Projected node lifetime (2 x AA, 2500 mAh)")
    ax.grid(alpha=0.25, which="both", lw=0.5)
    ax.legend(fontsize=8, frameon=False)
    fig.tight_layout()
    fig.savefig(os.path.join(OUT, "fig4_battery_life.png"))
    plt.close(fig)

    # -------------------------------------------------- console report
    print("=== energy per delivered event (J), nominal 1 % false-alarm rate ===")
    print("margin   A_fixed   B_adapt   C_filter  D_filter+adapt   D vs A")
    for s in savings:
        print(f"{s['margin0_db']:>5.1f}  {s['energy_per_event_A_j']:>9.3f} "
              f"{next(r for r in grid if r['policy']=='always_adaptive' and r['margin0_db']==s['margin0_db'])['energy_per_event_j']:>9.3f} "
              f"{s['energy_per_event_C_j']:>9.3f}  {s['energy_per_event_D_j']:>14.3f}  "
              f"{s['D_reduction_vs_A_pct']:>6.1f} %")
    print("\n=== recall (%) and projected life (years) ===")
    for s in savings:
        print(f"margin {s['margin0_db']:>4}: recall A {100*s['recall_A']:5.1f}%, "
              f"C {100*s['recall_C']:5.1f}%, D {100*s['recall_D']:5.1f}% | "
              f"life A {s['life_A_y']:.2f} y, D {s['life_D_y']:.2f} y")
    print("\n=== false-alarm sensitivity at 4 dB margin ===")
    for r in far_sweep:
        print(f"{r['policy']:>16}  FAR {r['false_alarm_rate']:<6}  "
              f"{r['energy_per_event_j']:8.3f} J/event   recall {100*r['recall']:.1f}%  "
              f"FA/week {r['false_alarms_delivered']:.0f}")
    print("\nwrote:", os.path.join(OUT, "summary.json"))


if __name__ == "__main__":
    main()
