"""Migration 0029: Add article_type column to articles table.

Values: 'cornerstone' | 'editorial' | 'generated'
Backfill from existing data:
  - template_slug IS NOT NULL                              → generated
  - template_slug IS NULL AND group_key IS NOT NULL        → cornerstone
  - template_slug IS NULL AND group_key IS NULL            → editorial
"""


def up(conn) -> None:
    conn.execute("""
        ALTER TABLE articles ADD COLUMN article_type TEXT NOT NULL DEFAULT 'editorial'
    """)
    conn.execute("""
        UPDATE articles SET article_type = 'generated'
        WHERE template_slug IS NOT NULL
    """)
    conn.execute("""
        UPDATE articles SET article_type = 'cornerstone'
        WHERE template_slug IS NULL AND group_key IS NOT NULL
    """)
    conn.execute("""
        CREATE INDEX IF NOT EXISTS idx_articles_article_type ON articles(article_type)
    """)
