"""add ai_messages table (chat history)

作者↔AI 往复留痕 append-only 侧表（AC-1）——非手稿真源，永不进 assemble()/agent 生成链。
复合索引 ix_ai_messages_project_chapter 手写 created_at DESC 表达式（沿用 chapter_reviews
证明可过 alembic check 的形态；autogenerate 无法可靠还原 DESC）。role CHECK 兜底二元枚举。

Revision ID: ceabd3c2c00d
Revises: f6a7b8c9d0e1
Create Date: 2026-07-09 16:35:14.948502
"""

from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision: str = "ceabd3c2c00d"
down_revision: str | None = "f6a7b8c9d0e1"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.create_table(
        "ai_messages",
        sa.Column("project_id", sa.Uuid(), nullable=False),
        sa.Column("chapter_no", sa.Integer(), nullable=True),
        sa.Column("thread_id", sa.Uuid(), nullable=False),
        sa.Column("seq", sa.Integer(), nullable=False),
        sa.Column("kind", sa.Text(), nullable=False),
        sa.Column("tool_key", sa.Text(), nullable=True),
        sa.Column("role", sa.Text(), nullable=False),
        sa.Column("content", sa.Text(), nullable=False),
        sa.Column(
            "meta",
            postgresql.JSONB(astext_type=sa.Text()),
            server_default=sa.text("'{}'"),
            nullable=False,
        ),
        sa.Column("id", sa.Uuid(), server_default=sa.text("gen_random_uuid()"), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.CheckConstraint("role IN ('author', 'ai')", name="ck_ai_messages_role"),
        sa.ForeignKeyConstraint(["project_id"], ["projects.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(
        "ix_ai_messages_project_chapter",
        "ai_messages",
        ["project_id", "chapter_no", sa.text("created_at DESC")],
        unique=False,
    )
    op.create_index(op.f("ix_ai_messages_project_id"), "ai_messages", ["project_id"], unique=False)


def downgrade() -> None:
    op.drop_index(op.f("ix_ai_messages_project_id"), table_name="ai_messages")
    op.drop_index("ix_ai_messages_project_chapter", table_name="ai_messages")
    op.drop_table("ai_messages")
