"""记录 task 标题来源，支持清空后安全地重新自动命名。

Revision ID: 0024
Revises: 0023
Create Date: 2026-07-31

新增 title_source：auto / manual / fixed，以及防止旧标题结果跨清空轮次写回的
auto_title_version。历史数据无法可靠区分“自动命名后又人工改名”，因此仅把仍
处于 auto_title_pending 的行回填为 auto；渠道与调度任务回填 fixed，其余保守为
manual，避免清空时覆盖人工标题。
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op


revision: str = "0024"
down_revision: Union[str, None] = "0023"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column(
        "tasks",
        sa.Column(
            "title_source",
            sa.Text(),
            nullable=False,
            server_default="manual",
        ),
    )
    op.add_column(
        "tasks",
        sa.Column(
            "auto_title_version",
            sa.Integer(),
            nullable=False,
            server_default="0",
        ),
    )
    op.execute(
        """
        UPDATE tasks
        SET title_source = 'fixed'
        WHERE channel <> 'web' OR scheduled_job_id IS NOT NULL
        """
    )
    op.execute(
        """
        UPDATE tasks
        SET title_source = 'auto'
        WHERE title_source = 'manual' AND auto_title_pending = true
        """
    )
    op.create_check_constraint(
        "ck_tasks_title_source",
        "tasks",
        "title_source IN ('auto', 'manual', 'fixed')",
    )


def downgrade() -> None:
    op.drop_constraint("ck_tasks_title_source", "tasks", type_="check")
    op.drop_column("tasks", "auto_title_version")
    op.drop_column("tasks", "title_source")
