-- Phase 27: Incident Frequency Snapshot 持久化
-- 2026-04-10 ogt: frequency_stats 只存記憶體/Redis(35天TTL)，重啟或超期即失
--   解決方案：在 incidents 表加 frequency_snapshot JSONB，建立 incident 時寫入快照
--   歷史按鈕優先讀 DB 快照，Redis AnomalyCounter 補充長期累積統計

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'incidents' AND column_name = 'frequency_snapshot'
    ) THEN
        ALTER TABLE incidents ADD COLUMN frequency_snapshot JSONB DEFAULT NULL;
        COMMENT ON COLUMN incidents.frequency_snapshot IS
            'Snapshot of AnomalyFrequency at incident creation time. '
            'Fields: anomaly_key, count_1h, count_24h, count_7d, count_30d, '
            'escalation_level, auto_repair_count, last_repair_action, '
            'human_approved_count, manual_resolved_count, cold_start_trust_count, total_resolution_count. '
            'Added 2026-04-10 (Phase 27).';
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS ix_incidents_frequency_snapshot_key
    ON incidents ((frequency_snapshot->>'anomaly_key'))
    WHERE frequency_snapshot IS NOT NULL;
