\pset pager off

\echo '=== 1. Objetos v0.3.14 ==='

SELECT
    to_regclass(
        'mv_loss_intelligence.context_governance_ui_actions'
    ) AS actions_table,
    to_regclass(
        'mv_reports_ucepsa_prod.li_context_governance_ui_queue_v1'
    ) AS queue_view,
    to_regclass(
        'mv_reports_ucepsa_prod.li_context_governance_ui_case_timeline_v1'
    ) AS timeline_view,
    to_regclass(
        'mv_reports_ucepsa_prod.li_context_governance_ui_recent_actions_v1'
    ) AS actions_view;

\echo '=== 2. Cola UI igual a la agenda diaria ==='

SELECT
    (
        SELECT COUNT(*)
        FROM
            mv_reports_ucepsa_prod
            .li_context_governance_ui_queue_v1
    ) AS ui_queue_rows,
    (
        SELECT COUNT(*)
        FROM
            mv_reports_ucepsa_prod
            .li_context_governance_daily_agenda_v1
    ) AS agenda_rows;

\echo '=== 3. Separación semántica de estados ==='

SELECT COUNT(*) AS invalid_ui_status_rows
FROM
    mv_reports_ucepsa_prod
    .li_context_governance_ui_queue_v1
WHERE incident_status NOT IN (
    'ACTIVE',
    'ENDED'
)
   OR review_status <> 'PENDING';

\echo '=== 4. Una decisión una sola vez ==='

SELECT COUNT(*) AS duplicate_ui_decisions
FROM (
    SELECT
        decision_group_key,
        COUNT(*) AS n
    FROM
        mv_reports_ucepsa_prod
        .li_context_governance_ui_queue_v1
    GROUP BY decision_group_key
    HAVING COUNT(*) > 1
) duplicated;

\echo '=== 5. Timeline contiene todos los casos pendientes ==='

SELECT COUNT(*) AS pending_cases_without_timeline
FROM
    mv_reports_ucepsa_prod
    .li_context_decision_group_cases_v1 c
WHERE c.case_review_status =
      'PENDING'
  AND NOT EXISTS (
      SELECT 1
      FROM
          mv_reports_ucepsa_prod
          .li_context_governance_ui_case_timeline_v1 t
      WHERE t.decision_group_key =
            c.decision_group_key
        AND t.case_id =
            c.case_id
  );

\echo '=== 6. Auditoría UI no oficial ==='

SELECT
    (
        SELECT COUNT(*)
        FROM
            mv_loss_intelligence
            .context_governance_ui_actions
        WHERE official_eligible
    ) AS official_ui_action_rows,
    (
        SELECT COUNT(*)
        FROM
            mv_reports_ucepsa_prod
            .li_context_governance_ui_queue_v1
        WHERE official_eligible
    ) AS official_ui_queue_rows,
    (
        SELECT COUNT(*)
        FROM
            mv_reports_ucepsa_prod
            .li_operator_stop_queue_v2
    ) AS official_operator_queue_rows;

\echo '=== 7. Acciones registradas ==='

SELECT
    ui_action_id,
    decision_group_key,
    selected_case_ids,
    answer_code,
    mapped_classification,
    actor_display_name,
    create_contexts,
    created_context_session_ids,
    status,
    created_at
FROM
    mv_reports_ucepsa_prod
    .li_context_governance_ui_recent_actions_v1
ORDER BY created_at DESC
LIMIT 20;
