from datetime import datetime, timedelta
from pathlib import Path

from sentinel.cloud.store import CloudStore
from sentinel.notifications.templates import NotificationTemplateEngine


def test_device_offline_online_transitions(tmp_path: Path):
    store = CloudStore(tmp_path / "cloud.db")
    store.initialize()
    old = (datetime.now() - timedelta(minutes=10)).isoformat(timespec="seconds")
    store.register_device(device_id="pi-1", equipment_id="FZ-1", now_iso=old, heartbeat_interval_seconds=15)
    events = store.sweep_offline(grace_seconds=60)
    assert len(events) == 1
    assert events[0]["event_type"] == "DEVICE_OFFLINE"
    assert store.devices()[0]["online"] == 0
    transition = store.heartbeat(device_id="pi-1", equipment_id="FZ-1")
    assert transition == "DEVICE_ONLINE"
    assert store.devices()[0]["online"] == 1


def test_cloud_measurement_deduplication(tmp_path: Path):
    store = CloudStore(tmp_path / "cloud.db")
    store.initialize()
    payload = {
        "source_id": "42",
        "recorded_at": "2026-08-14T10:00:00",
        "device_id": "pi-1",
        "equipment_id": "FZ-1",
        "internal_temperature_c": -20.1,
    }
    assert store.ingest_measurement(payload) is True
    assert store.ingest_measurement(payload) is False
    assert store.stats()["synced_measurements"] == 1


def test_professional_notification_template():
    subject, body = NotificationTemplateEngine().build({
        "alarm_id": 7,
        "equipment_id": "LCSB00510",
        "severity": "CRITICAL",
        "title": "High temperature",
        "message": "internal_temperature_c = -13.800 > -15.000",
        "opened_at": datetime.now().isoformat(timespec="seconds"),
        "step_order": 2,
    })
    assert "LCSB00510" in subject
    assert "Internal temperature: -13.800 °C" in body
    assert "Threshold: > -15.000 °C" in body
    assert "Escalation level: 2" in body
