from pathlib import Path
from tempfile import TemporaryDirectory

from sentinel.monitoring.store import MonitoringStore


def make_store(tmp: str) -> MonitoringStore:
    store = MonitoringStore(Path(tmp) / "monitoring.db")
    store.initialize()
    return store


def test_equipment_can_belong_to_multiple_groups_and_be_removed():
    with TemporaryDirectory() as tmp:
        store = make_store(tmp)
        g1 = store.create_group(group_code="A", display_name="A", site_code=None, description=None)
        g2 = store.create_group(group_code="B", display_name="B", site_code=None, description=None)
        store.assign_equipment_to_group(equipment_id="eq-1", group_id=g1)
        store.assign_equipment_to_group(equipment_id="eq-1", group_id=g2)
        assert len(store.get_equipment_group_map()["eq-1"]) == 2
        store.remove_equipment_from_group(equipment_id="eq-1", group_id=g1)
        assert [g["group_code"] for g in store.get_equipment_group_map()["eq-1"]] == ["B"]


def test_manual_resolution_lock_persists_until_condition_clear():
    with TemporaryDirectory() as tmp:
        store = make_store(tmp)
        alarm_id = store.open_or_update_alarm(
            equipment_id="eq-1", category="THRESHOLD", severity="ALARM", code="RULE-1",
            title="High temp", message="too warm", suppressed=False, suppression_schedule_id=None,
        )
        store.resolve_alarm(alarm_id, actor="SM", comment="Reviewed and resolved")
        assert store.is_resolution_locked("eq-1", "RULE-1")
        store.clear_resolution_lock("eq-1", "RULE-1")
        assert not store.is_resolution_locked("eq-1", "RULE-1")


def test_alarm_notification_plan_is_traceable_and_ack_stops_pending_steps():
    with TemporaryDirectory() as tmp:
        store = make_store(tmp)
        rule_id = store.create_alarm_rule(
            name="High temp", scope_type="EQUIPMENT", scope_id="eq-1", category="THRESHOLD",
            severity="ALARM", metric="internal_temperature_c", operator="above", threshold=-15,
        )
        store.add_alarm_rule_recipient(rule_id=rule_id, step_order=1, channel="EMAIL", recipient="a@example.org", delay_minutes=0)
        store.add_alarm_rule_recipient(rule_id=rule_id, step_order=2, channel="SMS", recipient="+352000", delay_minutes=10)
        alarm_id = store.open_or_update_alarm(
            equipment_id="eq-1", category="THRESHOLD", severity="ALARM", code=f"RULE-{rule_id}",
            title="High temp", message="too warm", suppressed=False, suppression_schedule_id=None,
        )
        store.queue_alarm_notifications(alarm_id=alarm_id, rule_id=rule_id)
        assert len(store.get_alarm_notifications(alarm_id)) == 2
        store.acknowledge_alarm(alarm_id, actor="SM", comment="Taking action")
        assert all(row["status"] == "CANCELLED" for row in store.get_alarm_notifications(alarm_id))
        events = store.alarm_events_for([alarm_id])[alarm_id]
        assert any(e["comment"] == "Taking action" for e in events)
