-- GetActiveAlarmsByLocationAndPriority: Count active alarms grouped by location and priority
-- Uses: idx_alarm_events_active, idx_alarm_events_clear, idx_alarm_event_data_lookup, idx_alarm_events_priority
-- Expected performance: <100ms on 37K rows, <200ms on 1M+ rows

SELECT 
  SUBSTRING_INDEX(SUBSTRING_INDEX(IFNULL(aed.strValue, ''), '/', 2), '/', -1) AS Location,
  CASE ae.priority
    WHEN 0 THEN 'Diagnostic'
    WHEN 1 THEN 'Low'
    WHEN 2 THEN 'Medium'
    WHEN 3 THEN 'High'
    WHEN 4 THEN 'Critical'
    ELSE 'Unknown'
  END AS Priority,
  COUNT(*) AS Count
FROM alarm_events ae FORCE INDEX (idx_alarm_events_active)
LEFT JOIN alarm_event_data aed FORCE INDEX (idx_alarm_event_data_lookup)
  ON aed.id = ae.id AND aed.propname = 'myTag'
WHERE ae.eventtype = 0
  AND ae.displaypath NOT LIKE '%System Startup%'
  AND ae.source NOT LIKE '%System Startup%'
  -- FORCE INDEX in NOT EXISTS ensures fast clear event lookup
  AND NOT EXISTS (
    SELECT 1 
    FROM alarm_events clr FORCE INDEX (idx_alarm_events_clear)
    WHERE clr.eventid = ae.eventid
      AND clr.eventtype = 1
  )
GROUP BY Location, ae.priority
ORDER BY Location, Priority;
