-- 044_red_flags_previews_snapshot.sql
-- Materialize TOP-5 row previews per red-flag recipe to a snapshot table.
-- Original landing was ~17s (13 recipe.fetch() calls running live, each 1-12s).
-- Now: single SELECT against this table → ~5ms.
--
-- Refresh: nightly from refresh-mvs.sh after KPI snapshot refresh.
--
-- Mirrors the RecipeRow interface (src/lib/recipes.ts):
--   primary, primaryHref, secondary, metric, metricRaw, detail, badge.{label,tone}
--
-- For each of the 13 RED_FLAG_SLUGS in src/pages/achizitii/red-flags.astro,
-- we re-implement the SQL inline (returning the formatted output the page
-- needs) and select TOP-5 per slug.

CREATE SCHEMA IF NOT EXISTS public_kpi;

CREATE TABLE IF NOT EXISTS public_kpi.red_flags_previews (
  slug         text NOT NULL,
  position     smallint NOT NULL,
  primary_text text,
  primary_href text,
  secondary    text,
  metric       text,
  metric_raw   numeric,
  detail       text,
  badge_label  text,
  badge_tone   text,
  computed_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (slug, position)
);

COMMENT ON TABLE public_kpi.red_flags_previews IS
  'Top-5 row previews per red-flag recipe. Refreshed nightly via refresh-mvs.sh. Read once per landing page load instead of running 13 live cross-source queries.';

-- ─────────────────────────────────────────────────────────────────────────────
-- Helper: RON formatter mirroring fmtRON() in src/lib/recipes.ts.
-- Returns short-form: "1.2 mld", "12.3 mil", "456K", "789".
CREATE OR REPLACE FUNCTION public_kpi.fmt_ron(v numeric) RETURNS text AS $$
BEGIN
  IF v IS NULL OR v <= 0 THEN RETURN '0'; END IF;
  IF v >= 1000000000 THEN RETURN to_char(v / 1000000000.0, 'FM999990.0') || ' mld'; END IF;
  IF v >= 1000000    THEN RETURN to_char(v / 1000000.0,    'FM999990.0') || ' mil'; END IF;
  IF v >= 1000       THEN RETURN to_char(round(v / 1000.0), 'FM999999990') || 'K'; END IF;
  RETURN to_char(round(v), 'FM999999990');
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- ─────────────────────────────────────────────────────────────────────────────

CREATE OR REPLACE FUNCTION public_kpi.refresh_red_flags_previews() RETURNS void AS $$
BEGIN
  DELETE FROM public_kpi.red_flags_previews;

  -- ───── firme-quadra-pipe-public ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH ben AS (
    SELECT b.cui, COUNT(*) AS anunturi_eu, SUM(l.buget_lei)::numeric AS buget_eu
    FROM fonduri.beneficiar_anunt b
    LEFT JOIN fonduri.beneficiar_anunt_lot l ON l.anunt_id = b.id
    WHERE b.cui IS NOT NULL GROUP BY b.cui
  ),
  seap AS (
    SELECT supplier_cui AS cui, COUNT(*) AS contracte, SUM(awarded_value)::numeric AS valoare
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  afir AS (
    SELECT cui, COUNT(*) AS plati,
           SUM(COALESCE(ue_total, feadr_total, fega_total, op_amount, 0))::numeric AS afir_lei
    FROM fonduri.afir_plati WHERE cui IS NOT NULL GROUP BY cui
  ),
  regas AS (
    SELECT cui, COUNT(*) AS nr_ajutoare,
           SUM(ajutor_acordat_subcategorie)::numeric AS regas_lei
    FROM regas.ajutoare WHERE cui IS NOT NULL GROUP BY cui
  ),
  ranked AS (
    SELECT b.cui, e.name, e.adr_judet,
           b.buget_eu, s.valoare AS seap_lei, a.afir_lei, r.regas_lei,
           (COALESCE(b.buget_eu,0) + COALESCE(s.valoare,0) + COALESCE(a.afir_lei,0) + COALESCE(r.regas_lei,0))::numeric AS total_combined,
           ROW_NUMBER() OVER (ORDER BY (COALESCE(b.buget_eu,0) + COALESCE(s.valoare,0) + COALESCE(a.afir_lei,0) + COALESCE(r.regas_lei,0)) DESC NULLS LAST) AS rn
    FROM ben b
    JOIN seap s ON s.cui = b.cui
    JOIN afir a ON a.cui = b.cui
    JOIN regas r ON r.cui = b.cui
    JOIN firms.entities e ON e.cui = b.cui
  )
  SELECT 'firme-quadra-pipe-public', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         public_kpi.fmt_ron(total_combined) || ' RON',
         total_combined,
         'EU: ' || public_kpi.fmt_ron(COALESCE(buget_eu,0)) || ' · SEAP: ' || public_kpi.fmt_ron(COALESCE(seap_lei,0)) || ' · AFIR: ' || public_kpi.fmt_ron(COALESCE(afir_lei,0)) || ' · RegAS: ' || public_kpi.fmt_ron(COALESCE(regas_lei,0)) || ' RON',
         '🔱 QUADRA pipe', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── firme-triplu-pipe-public ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH ben AS (
    SELECT b.cui, COUNT(*) AS anunturi_eu, SUM(l.buget_lei)::numeric AS buget_eu
    FROM fonduri.beneficiar_anunt b
    LEFT JOIN fonduri.beneficiar_anunt_lot l ON l.anunt_id = b.id
    WHERE b.cui IS NOT NULL GROUP BY b.cui
  ),
  seap AS (
    SELECT supplier_cui AS cui, COUNT(*) AS contracte, SUM(awarded_value)::numeric AS valoare
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  afir AS (
    SELECT cui, COUNT(*) AS plati,
           SUM(COALESCE(ue_total, feadr_total, fega_total, op_amount, 0))::numeric AS afir_lei
    FROM fonduri.afir_plati WHERE cui IS NOT NULL GROUP BY cui
  ),
  ranked AS (
    SELECT b.cui, e.name, e.adr_judet,
           b.anunturi_eu, b.buget_eu, s.contracte, s.valoare AS seap_lei, a.plati, a.afir_lei,
           (COALESCE(b.buget_eu,0) + COALESCE(s.valoare,0) + COALESCE(a.afir_lei,0))::numeric AS total_combined,
           ROW_NUMBER() OVER (ORDER BY (COALESCE(b.buget_eu,0) + COALESCE(s.valoare,0) + COALESCE(a.afir_lei,0)) DESC NULLS LAST) AS rn
    FROM ben b
    JOIN seap s ON s.cui = b.cui
    JOIN afir a ON a.cui = b.cui
    JOIN firms.entities e ON e.cui = b.cui
  )
  SELECT 'firme-triplu-pipe-public', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         public_kpi.fmt_ron(total_combined) || ' RON',
         total_combined,
         'EU privat: ' || anunturi_eu || ' / ' || public_kpi.fmt_ron(COALESCE(buget_eu,0)) || ' · SEAP: ' || contracte || ' / ' || public_kpi.fmt_ron(COALESCE(seap_lei,0)) || ' · AFIR: ' || plati || ' / ' || public_kpi.fmt_ron(COALESCE(afir_lei,0)) || ' RON',
         '🔱 triplu pipe', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── firme-datornice-cu-contracte-seap ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH agg AS (
    SELECT d.cui, d.name,
           MIN(d.publication_date) AS pub_date,
           MIN(d.period_label) AS period_label,
           MAX(d.debt_total) AS debt_total,
           MAX(d.debtor_category) AS debtor_category,
           COUNT(DISTINCT a.id) AS contracte,
           SUM(a.awarded_value)::numeric AS contracte_lei,
           MAX(a.publication_date::date) AS ultim_contract
    FROM anaf.datornici d
    JOIN seap.announcements a
      ON a.supplier_cui = d.cui
     AND a.publication_date::date > d.publication_date
    WHERE a.awarded_value IS NOT NULL AND a.awarded_value > 0
    GROUP BY d.cui, d.name
    HAVING SUM(a.awarded_value) > 100000
  ),
  ranked AS (
    SELECT agg.*, e.adr_judet AS judet,
           ROW_NUMBER() OVER (ORDER BY contracte_lei DESC NULLS LAST) AS rn
    FROM agg LEFT JOIN firms.entities e ON e.cui = agg.cui
  )
  SELECT 'firme-datornice-cu-contracte-seap', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN judet IS NOT NULL THEN ' · ' || judet ELSE '' END || ' · ' || COALESCE(period_label, 'T1 2016'),
         public_kpi.fmt_ron(contracte_lei) || ' RON',
         contracte_lei,
         'Datorie ' || public_kpi.fmt_ron(COALESCE(debt_total,0)) || ' RON (' || COALESCE(debtor_category::text, '') || ') · ' || contracte || ' contracte · ultim ' || COALESCE(ultim_contract::text, '?'),
         '🚨 datornic + contract', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── donatori-care-au-castigat-seap ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH don AS (
    SELECT donator_cui AS cui,
           MIN(donator_nume) AS donator,
           COUNT(*) AS nr_donatii,
           SUM(suma_lei)::numeric AS total_donatii,
           array_agg(DISTINCT partid_id ORDER BY partid_id) AS partide,
           MIN(an) AS prima, MAX(an) AS ultima
    FROM aep.donatii_pj
    WHERE donator_cui IS NOT NULL
    GROUP BY donator_cui
  ),
  seap AS (
    SELECT supplier_cui AS cui,
           COUNT(*) AS contracte,
           SUM(awarded_value)::numeric AS contracte_lei,
           COUNT(DISTINCT authority_cui) AS autoritati
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  ranked AS (
    SELECT d.cui, COALESCE(e.name, d.donator) AS firma, e.adr_judet AS judet,
           d.nr_donatii, d.total_donatii, d.partide, d.prima, d.ultima,
           s.contracte, s.contracte_lei, s.autoritati,
           ROW_NUMBER() OVER (ORDER BY s.contracte_lei DESC NULLS LAST) AS rn
    FROM don d
    JOIN seap s ON s.cui = d.cui
    LEFT JOIN firms.entities e ON e.cui = d.cui
    WHERE s.contracte_lei > 100000
  )
  SELECT 'donatori-care-au-castigat-seap', rn::smallint,
         COALESCE(firma, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN judet IS NOT NULL THEN ' · ' || judet ELSE '' END || ' · partide: ' || array_to_string(COALESCE(partide, ARRAY[]::text[]), ', '),
         public_kpi.fmt_ron(contracte_lei) || ' RON',
         contracte_lei,
         nr_donatii || ' donații (' || public_kpi.fmt_ron(COALESCE(total_donatii,0)) || ' RON, ' || prima || '-' || ultima || ') · ' || contracte || ' contracte la ' || autoritati || ' autorități',
         '🗳️ donator + furnizor', 'warn'
    FROM ranked WHERE rn <= 5;

  -- ───── donatori-politici-care-datoreaza-statului ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH aep_agg AS (
    SELECT donator_cui AS cui,
           SUM(suma_lei)::numeric AS total_donat,
           array_agg(DISTINCT partid_id ORDER BY partid_id) FILTER (WHERE partid_id IS NOT NULL) AS partide,
           COUNT(*) AS nr_donatii,
           MIN(an) AS prima_an, MAX(an) AS ultima_an
    FROM aep.donatii_pj
    WHERE donator_cui IS NOT NULL
    GROUP BY donator_cui
  ),
  seap_supplier AS (
    SELECT supplier_cui AS cui,
           COUNT(*) AS contracte,
           SUM(awarded_value)::numeric AS valoare_seap
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  ranked AS (
    SELECT d.cui, d.period_label, d.debt_total::numeric AS debt_total,
           a.total_donat, a.partide, a.nr_donatii, a.prima_an, a.ultima_an,
           e.name, e.adr_judet,
           COALESCE(s.contracte, 0) AS contracte_seap,
           COALESCE(s.valoare_seap, 0)::numeric AS valoare_seap,
           ROW_NUMBER() OVER (ORDER BY d.debt_total DESC NULLS LAST) AS rn
    FROM aep_agg a
    JOIN anaf.datornici_latest d ON d.cui = a.cui
    LEFT JOIN firms.entities e ON e.cui = a.cui
    LEFT JOIN seap_supplier s ON s.cui = a.cui
  )
  SELECT 'donatori-politici-care-datoreaza-statului', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END || ' · partide: ' || array_to_string(COALESCE(partide, ARRAY[]::text[]), ', ') || ' (' || prima_an || '–' || ultima_an || ')',
         public_kpi.fmt_ron(debt_total) || ' RON datorie',
         debt_total,
         '🗳️ donat ' || public_kpi.fmt_ron(COALESCE(total_donat,0)) || ' RON · 🚨 datornic ' || COALESCE(period_label,'') ||
           CASE WHEN contracte_seap > 0 THEN ' · 📜 ' || contracte_seap || ' contracte SEAP (' || public_kpi.fmt_ron(valoare_seap) || ' RON)' ELSE '' END,
         '🚨 donator + datornic', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── donatori-politici-care-contesta-la-cnsc ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH aep_agg AS (
    SELECT donator_cui AS cui,
           SUM(suma_lei)::numeric AS total_donat,
           array_agg(DISTINCT partid_id ORDER BY partid_id) FILTER (WHERE partid_id IS NOT NULL) AS partide,
           COUNT(*) AS nr_donatii,
           MAX(an) AS ultima_an
    FROM aep.donatii_pj
    WHERE donator_cui IS NOT NULL
    GROUP BY donator_cui
  ),
  seap AS (
    SELECT supplier_cui AS cui,
           COUNT(*) AS contracte,
           SUM(awarded_value)::numeric AS valoare_seap
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  ranked AS (
    SELECT a.cui, e.name, e.adr_judet,
           a.total_donat, a.partide, a.ultima_an,
           c.contestations_filed,
           COALESCE(s.contracte, 0) AS contracte_seap,
           COALESCE(s.valoare_seap, 0)::numeric AS valoare_seap,
           ROW_NUMBER() OVER (ORDER BY (a.total_donat * c.contestations_filed) DESC NULLS LAST) AS rn
    FROM aep_agg a
    JOIN cnsc.mv_per_contestator_cui c ON c.cui = a.cui
    LEFT JOIN firms.entities e ON e.cui = a.cui
    LEFT JOIN seap s ON s.cui = a.cui
  )
  SELECT 'donatori-politici-care-contesta-la-cnsc', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END || ' · partide: ' || array_to_string(COALESCE(partide, ARRAY[]::text[]), ', ') || ' (ultima ' || ultima_an || ')',
         public_kpi.fmt_ron(total_donat) || ' × ' || contestations_filed,
         (total_donat * contestations_filed)::numeric,
         '🗳️ donat ' || public_kpi.fmt_ron(total_donat) || ' RON · ⚖️ ' || contestations_filed || ' contestații CNSC' ||
           CASE WHEN contracte_seap > 0 THEN ' · 📜 ' || contracte_seap || ' contracte SEAP (' || public_kpi.fmt_ron(valoare_seap) || ' RON)' ELSE '' END,
         '🗳️⚖️ donator + contestator', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── energie-licentiati-anre-datornici-anaf ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH seap AS (
    SELECT supplier_cui AS cui,
           COUNT(*) AS contracte,
           SUM(awarded_value)::numeric AS valoare_seap
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  ranked AS (
    SELECT a.cui, e.name, e.adr_judet,
           a.nr_active, a.nr_expirate, a.surse,
           d.debt_total::numeric AS debt_total, d.period_label,
           COALESCE(s.contracte, 0) AS contracte_seap,
           COALESCE(s.valoare_seap, 0)::numeric AS valoare_seap,
           ROW_NUMBER() OVER (ORDER BY d.debt_total DESC NULLS LAST) AS rn
    FROM anre.mv_licente_per_cui a
    JOIN anaf.datornici_latest d ON d.cui = a.cui
    LEFT JOIN firms.entities e ON e.cui = a.cui
    LEFT JOIN seap s ON s.cui = a.cui
    WHERE a.nr_active > 0
  )
  SELECT 'energie-licentiati-anre-datornici-anaf', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END || ' · 🔌 ' || nr_active || ' licențe active (' || array_to_string(COALESCE(surse, ARRAY[]::text[]), '/') || ')' || CASE WHEN nr_expirate > 0 THEN ', ' || nr_expirate || ' expirate' ELSE '' END,
         public_kpi.fmt_ron(debt_total) || ' RON datorie',
         debt_total,
         '🚨 datornic ' || COALESCE(period_label, '') ||
           CASE WHEN contracte_seap > 0 THEN ' · 📜 ' || contracte_seap || ' contracte SEAP (' || public_kpi.fmt_ron(valoare_seap) || ' RON)' ELSE '' END,
         '🚨 ANRE + datornic', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── autoritati-dubla-alerta-cdc-cnsc ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH cdc AS (
    SELECT audited_entity_cui AS cui,
           COUNT(*) AS audit_count,
           array_agg(DISTINCT audit_type) FILTER (WHERE audit_type IS NOT NULL) AS audit_types
    FROM curteacont.rapoarte
    WHERE audited_entity_cui IS NOT NULL
      AND publication_date >= now() - interval '5 years'
    GROUP BY audited_entity_cui
    HAVING COUNT(*) >= 2
  ),
  cnsc_ AS (
    SELECT cui, contestation_count
    FROM cnsc.mv_per_authority_cui
    WHERE contestation_count >= 3
  ),
  seap AS (
    SELECT authority_cui AS cui,
           COUNT(*) AS proceduri,
           SUM(COALESCE(awarded_value, estimated_value))::numeric AS valoare
    FROM seap.announcements
    WHERE authority_cui IS NOT NULL
    GROUP BY authority_cui
  ),
  ranked AS (
    SELECT a.cui, e.name, e.adr_judet,
           a.audit_count, a.audit_types,
           c.contestation_count,
           (a.audit_count + c.contestation_count) AS total_signals,
           COALESCE(s.proceduri, 0) AS proceduri,
           COALESCE(s.valoare, 0)::numeric AS valoare,
           ROW_NUMBER() OVER (ORDER BY (a.audit_count + c.contestation_count) DESC, c.contestation_count DESC) AS rn
    FROM cdc a
    JOIN cnsc_ c ON c.cui = a.cui
    LEFT JOIN firms.entities e ON e.cui = a.cui
    LEFT JOIN seap s ON s.cui = a.cui
  )
  SELECT 'autoritati-dubla-alerta-cdc-cnsc', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/autoritate/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         total_signals || ' semnale',
         total_signals::numeric,
         '📋 ' || audit_count || ' audituri (' || array_to_string(COALESCE(audit_types, ARRAY[]::text[]), '/') || ') · ⚖️ ' || contestation_count || ' contestații CNSC · ' || proceduri || ' proceduri SEAP · ' || public_kpi.fmt_ron(COALESCE(valoare,0)) || ' RON',
         '🚨 dublă alertă', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── autoritati-contestate-cnsc ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH ranked AS (
    SELECT m.cui, m.contestation_count,
           m.first_contestation_date, m.last_contestation_date,
           e.name, e.adr_judet,
           COALESCE(s.proceduri, 0) AS proceduri,
           COALESCE(s.valoare, 0)::numeric AS valoare,
           ROW_NUMBER() OVER (ORDER BY m.contestation_count DESC) AS rn
    FROM cnsc.mv_per_authority_cui m
    LEFT JOIN firms.entities e ON e.cui = m.cui
    LEFT JOIN (
      SELECT authority_cui,
             COUNT(*) AS proceduri,
             SUM(awarded_value)::numeric AS valoare
      FROM seap.announcements
      WHERE authority_cui IS NOT NULL
      GROUP BY authority_cui
    ) s ON s.authority_cui = m.cui
  )
  SELECT 'autoritati-contestate-cnsc', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/autoritate/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         contestation_count || ' contestații',
         contestation_count::numeric,
         proceduri || ' proceduri SEAP · ' || public_kpi.fmt_ron(COALESCE(valoare,0)) || ' RON · contestații ' ||
           COALESCE(extract(year FROM first_contestation_date)::text, '?') || '–' ||
           COALESCE(extract(year FROM last_contestation_date)::text, '?'),
         '⚖️ CNSC', 'warn'
    FROM ranked WHERE rn <= 5;

  -- ───── energie-fara-licenta ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH energy_seap AS (
    SELECT a.supplier_cui,
           COUNT(*) AS contracte,
           SUM(a.awarded_value)::numeric AS valoare,
           COUNT(DISTINCT a.authority_cui) AS autoritati,
           array_agg(DISTINCT substr(a.cpv_code, 1, 4)) AS cpv_prefs
    FROM seap.announcements a
    WHERE a.supplier_cui IS NOT NULL
      AND a.awarded_value > 0
      AND a.cpv_code LIKE '09%'
    GROUP BY a.supplier_cui
  ),
  ranked AS (
    SELECT s.supplier_cui AS cui, e.name, e.adr_judet,
           s.contracte, s.valoare, s.autoritati, s.cpv_prefs,
           ROW_NUMBER() OVER (ORDER BY s.valoare DESC NULLS LAST) AS rn
    FROM energy_seap s
    LEFT JOIN anre.mv_licente_per_cui m ON m.cui = s.supplier_cui
    JOIN firms.entities e ON e.cui = s.supplier_cui
    WHERE m.cui IS NULL
  )
  SELECT 'energie-fara-licenta', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         public_kpi.fmt_ron(valoare) || ' RON',
         valoare,
         contracte || ' contracte · ' || autoritati || ' autorități · CPV ' || array_to_string((COALESCE(cpv_prefs, ARRAY[]::text[]))[1:5], ', '),
         'fără licență ANRE', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── telco-fara-licenta ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH telco_seap AS (
    SELECT a.supplier_cui,
           COUNT(*) AS contracte,
           SUM(a.awarded_value)::numeric AS valoare,
           COUNT(DISTINCT a.authority_cui) AS autoritati,
           array_agg(DISTINCT substr(a.cpv_code, 1, 4)) AS cpv_prefs
    FROM seap.announcements a
    WHERE a.supplier_cui IS NOT NULL
      AND a.awarded_value > 0
      AND a.cpv_code LIKE '64%'
    GROUP BY a.supplier_cui
  ),
  ranked AS (
    SELECT s.supplier_cui AS cui, e.name, e.adr_judet,
           s.contracte, s.valoare, s.autoritati, s.cpv_prefs,
           ROW_NUMBER() OVER (ORDER BY s.valoare DESC NULLS LAST) AS rn
    FROM telco_seap s
    LEFT JOIN ancom.mv_operatori_per_cui m ON m.cui = s.supplier_cui
    JOIN firms.entities e ON e.cui = s.supplier_cui
    WHERE m.cui IS NULL
  )
  SELECT 'telco-fara-licenta', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         public_kpi.fmt_ron(valoare) || ' RON',
         valoare,
         contracte || ' contracte · ' || autoritati || ' autorități · CPV ' || array_to_string((COALESCE(cpv_prefs, ARRAY[]::text[]))[1:5], ', '),
         'fără autorizare ANCOM', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── stat-actionar-seap ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH aaas_agg AS (
    SELECT cui, max_state_share_pct, total_debt_to_state_lei, statusuri
    FROM aaas.mv_per_cui
  ),
  seap AS (
    SELECT supplier_cui AS cui,
           COUNT(*) AS contracte,
           SUM(awarded_value)::numeric AS total_lei,
           COUNT(DISTINCT authority_cui) AS autoritati
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  ranked AS (
    SELECT a.cui,
           COALESCE(e.name, f.name) AS firma,
           e.adr_judet AS judet,
           a.max_state_share_pct,
           a.total_debt_to_state_lei,
           a.statusuri,
           s.contracte, s.total_lei, s.autoritati,
           ROW_NUMBER() OVER (ORDER BY s.total_lei DESC NULLS LAST) AS rn
    FROM aaas_agg a
    JOIN seap s ON s.cui = a.cui
    LEFT JOIN firms.entities e ON e.cui = a.cui
    LEFT JOIN aaas.firme f    ON f.cui = a.cui
  )
  SELECT 'stat-actionar-seap', rn::smallint,
         COALESCE(firma, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN judet IS NOT NULL THEN ' · ' || judet ELSE '' END || ' · stat ' || CASE WHEN max_state_share_pct IS NOT NULL THEN to_char(max_state_share_pct, 'FM999990.0') || '%' ELSE '?' END || ' · ' || array_to_string(COALESCE(statusuri, ARRAY[]::text[]), ', '),
         public_kpi.fmt_ron(total_lei) || ' RON',
         total_lei,
         contracte || ' contracte la ' || autoritati || ' autorități' ||
           CASE WHEN total_debt_to_state_lei IS NOT NULL AND total_debt_to_state_lei > 0
                THEN ' · datorii la stat ' || public_kpi.fmt_ron(total_debt_to_state_lei) || ' RON'
                ELSE '' END,
         '🏛️ stat→stat', 'risk'
    FROM ranked WHERE rn <= 5;

  -- ───── firme-cu-ajutor-de-stat-si-seap ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH regas_amount AS (
    SELECT cui,
           COUNT(*) AS nr_ajutoare,
           SUM(ajutor_acordat_subcategorie) AS total_ajutor,
           COUNT(DISTINCT id_masura) AS nr_masuri,
           COUNT(DISTINCT finantator) AS nr_finantatori
    FROM regas.ajutoare
    WHERE cui IS NOT NULL
    GROUP BY cui
  ),
  seap_amount AS (
    SELECT supplier_cui AS cui,
           COUNT(*) AS contracte_seap,
           SUM(awarded_value) AS valoare_seap,
           COUNT(DISTINCT authority_cui) AS autoritati
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  ranked AS (
    SELECT r.cui, e.name, e.adr_judet,
           r.nr_ajutoare, r.total_ajutor::numeric AS total_ajutor, r.nr_finantatori,
           s.contracte_seap, s.valoare_seap::numeric AS valoare_seap, s.autoritati,
           (COALESCE(r.total_ajutor,0) + COALESCE(s.valoare_seap,0))::numeric AS total_combined,
           ROW_NUMBER() OVER (ORDER BY (COALESCE(r.total_ajutor,0) + COALESCE(s.valoare_seap,0)) DESC NULLS LAST) AS rn
    FROM regas_amount r
    JOIN seap_amount s ON s.cui = r.cui
    JOIN firms.entities e ON e.cui = r.cui
    WHERE COALESCE(r.total_ajutor,0) + COALESCE(s.valoare_seap,0) > 0
  )
  SELECT 'firme-cu-ajutor-de-stat-si-seap', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         public_kpi.fmt_ron(total_combined) || ' RON',
         total_combined,
         'Ajutor stat: ' || nr_ajutoare || ' ajutoare / ' || public_kpi.fmt_ron(COALESCE(total_ajutor,0)) || ' RON la ' || nr_finantatori || ' finanțatori · SEAP: ' || contracte_seap || ' contracte / ' || public_kpi.fmt_ron(COALESCE(valoare_seap,0)) || ' RON la ' || autoritati || ' autorități',
         'Ajutor + SEAP', 'warn'
    FROM ranked WHERE rn <= 5;

  -- ───── firme-cu-fonduri-eu-si-seap ─────
  INSERT INTO public_kpi.red_flags_previews
    (slug, position, primary_text, primary_href, secondary, metric, metric_raw, detail, badge_label, badge_tone)
  WITH ben_amount AS (
    SELECT b.cui,
           COUNT(*) AS anunturi_eu,
           SUM(l.buget_lei) AS buget_eu
    FROM fonduri.beneficiar_anunt b
    LEFT JOIN fonduri.beneficiar_anunt_lot l ON l.anunt_id = b.id
    WHERE b.cui IS NOT NULL
    GROUP BY b.cui
  ),
  seap_amount AS (
    SELECT supplier_cui AS cui,
           COUNT(*) AS contracte_seap,
           SUM(awarded_value) AS valoare_seap,
           COUNT(DISTINCT authority_cui) AS autoritati
    FROM seap.announcements
    WHERE supplier_cui IS NOT NULL AND awarded_value > 0
    GROUP BY supplier_cui
  ),
  ranked AS (
    SELECT b.cui, e.name, e.adr_judet,
           b.anunturi_eu, b.buget_eu::numeric AS buget_eu,
           s.contracte_seap, s.valoare_seap::numeric AS valoare_seap, s.autoritati,
           (COALESCE(b.buget_eu,0) + COALESCE(s.valoare_seap,0))::numeric AS total_combined,
           ROW_NUMBER() OVER (ORDER BY (COALESCE(b.buget_eu,0) + COALESCE(s.valoare_seap,0)) DESC NULLS LAST) AS rn
    FROM ben_amount b
    JOIN seap_amount s ON s.cui = b.cui
    JOIN firms.entities e ON e.cui = b.cui
    WHERE COALESCE(b.buget_eu,0) + COALESCE(s.valoare_seap,0) > 0
  )
  SELECT 'firme-cu-fonduri-eu-si-seap', rn::smallint,
         COALESCE(name, 'CUI ' || cui),
         '/achizitii/firma/' || cui,
         'CUI ' || cui || CASE WHEN adr_judet IS NOT NULL THEN ' · ' || adr_judet ELSE '' END,
         public_kpi.fmt_ron(total_combined) || ' RON',
         total_combined,
         'EU: ' || anunturi_eu || ' anunțuri / ' || public_kpi.fmt_ron(COALESCE(buget_eu,0)) || ' RON · SEAP: ' || contracte_seap || ' contracte / ' || public_kpi.fmt_ron(COALESCE(valoare_seap,0)) || ' RON la ' || autoritati || ' autorități',
         'EU + SEAP', 'warn'
    FROM ranked WHERE rn <= 5;

END;
$$ LANGUAGE plpgsql;

-- Initial populate
SELECT public_kpi.refresh_red_flags_previews();

SELECT slug, COUNT(*) AS rows
  FROM public_kpi.red_flags_previews
 GROUP BY slug
 ORDER BY slug;
