-- GetActiveAlarmsByLocationAndPriority: Count active alarms grouped by location and priority
-- Uses: idx_alarm_events_eventid, idx_alarm_event_data_lookup
-- Expected performance: <1 second

-- Active alarm = latest event per eventid is eventtype=0 (Ignition alarm pattern)

SELECT 
  -- Use myLocation property directly (99.96% coverage) - MUCH faster than parsing tags!
  IFNULL(loc.strValue, '') 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
INNER JOIN (
  -- Find latest event per eventid where latest event is type 0 (active)
  SELECT lat.eventid, lat.latest_id
  FROM (
    SELECT eventid, MAX(id) as latest_id
    FROM alarm_events
    WHERE eventid IS NOT NULL
    GROUP BY eventid
  ) lat
  INNER JOIN alarm_events latest_event ON latest_event.id = lat.latest_id
  WHERE latest_event.eventtype = 0
    AND latest_event.displaypath NOT LIKE '%System Startup%'
    AND latest_event.source NOT LIKE '%System Startup%'
    AND latest_event.displaypath NOT LIKE '%System Shutdown%'
    AND latest_event.source NOT LIKE '%System Shutdown%'
) active ON ae.id = active.latest_id
LEFT JOIN alarm_event_data loc FORCE INDEX (idx_alarm_event_data_lookup)
  ON loc.id = ae.id AND loc.propname = 'myLocation'
GROUP BY Location, ae.priority
ORDER BY Location, Priority;
