-- ============================================================
-- 002a_diagnostic_episode_number.sql
-- 诊断脚本：将 episodes.episode_number 从全局 UNIQUE 改为 (air_year, episode_number) 复合 UNIQUE
-- 执行方式: psql -U postgres -d milsci_dev -f 002a_diagnostic_episode_number.sql
-- 前置条件：先设 $env:PGCLIENTENCODING="UTF8"
-- ============================================================

-- 三项诊断（任一异常停下找制片人）
SELECT
  'total_rows'           as check_name,
  count(*)               as value
FROM episodes
UNION ALL
SELECT
  'null_air_date'        as check_name,
  count(*)               as value
FROM episodes
WHERE air_date IS NULL
UNION ALL
SELECT
  'duplicate_year_epnum' as check_name,
  count(*)               as value
FROM (
  SELECT
    EXTRACT(YEAR FROM air_date)::int as air_year,
    episode_number
  FROM episodes
  WHERE original_episode_id IS NULL
  GROUP BY 1, 2
  HAVING count(*) > 1
) as dup;