#!/usr/bin/env bash
set -euo pipefail
#
# One-time: consolidate existing duplicate container_crash issues by
# (container_name, cause), matching the going-forward (container, cause) dedup
# in whp-monitor-poll.py / whp_monitor_core.py compute_signature(kind='crash').
# These were previously keyed on site_id (0 for server-wide containers like
# haproxy-manager) + a 10-min bucket, so every auto-restart spawned a new row.
# Keep one open row per (container, cause) with the summed count + the new
# signature so future events increment it; mark the rest 'fixed'. Idempotent;
# never aborts the update.
#
echo "[dedup-container-crash] consolidating duplicate container_crash issues by (container, cause)"

mysql whp <<'SQL' 2>&1 || { echo "[dedup-container-crash] skipped (non-fatal)"; exit 0; }
SELECT CONCAT('[dedup-container-crash] before: ',
              COUNT(*), ' open container_crash rows, ',
              COUNT(DISTINCT container_name, subsystem), ' distinct (container,cause)') AS msg
FROM ai_monitor_issues
WHERE status='open' AND category='container_crash' AND container_name IS NOT NULL;

START TRANSACTION;
DROP TEMPORARY TABLE IF EXISTS _cc;
CREATE TEMPORARY TABLE _cc AS
  SELECT container_name, subsystem,
         MIN(id) AS keeper_id, SUM(occurrence_count) AS total, MAX(last_seen) AS maxlast
  FROM ai_monitor_issues
  WHERE status='open' AND category='container_crash' AND container_name IS NOT NULL
  GROUP BY container_name, subsystem;

UPDATE ai_monitor_issues t JOIN _cc d ON t.id = d.keeper_id
  SET t.occurrence_count = d.total,
      t.last_seen        = d.maxlast,
      t.signature        = SHA2(CONCAT('crash:', t.container_name, ':', COALESCE(t.subsystem, '')), 256);

UPDATE ai_monitor_issues t
  JOIN _cc d ON t.container_name = d.container_name AND (t.subsystem <=> d.subsystem)
  SET t.status = 'fixed',
      t.auto_resolved_at = COALESCE(t.auto_resolved_at, NOW()),
      t.status_changed_by = 'dedup-merge',
      t.status_changed_at = NOW()
  WHERE t.status = 'open' AND t.id <> d.keeper_id;

DROP TEMPORARY TABLE _cc;
COMMIT;

SELECT CONCAT('[dedup-container-crash] after:  ',
              COUNT(*), ' open container_crash rows') AS msg
FROM ai_monitor_issues
WHERE status='open' AND category='container_crash' AND container_name IS NOT NULL;
SQL

echo "[dedup-container-crash] done"
