"""LangGraph checkpoint tables: lg_checkpoints, lg_checkpoint_writes

Revision ID: c9d0e1f2a3b4
Revises: b8c9d0e1f2a3
Create Date: 2026-10-29

For services/graph_checkpointer.SqlCheckpointSaver (Phase 4), used only when
LANGGRAPH_CHECKPOINTER=postgres. One row per saved graph state, and one per
pending write of a paused run. bearer_token is never stored in either.
The column definitions must match graph_checkpointer.checkpoints_table /
writes_table.
"""
from alembic import op
import sqlalchemy as sa


revision = "c9d0e1f2a3b4"
down_revision = "b8c9d0e1f2a3"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "lg_checkpoints",
        sa.Column("thread_id", sa.String(255), nullable=False),
        sa.Column("checkpoint_ns", sa.String(255), nullable=False, server_default=""),
        sa.Column("checkpoint_id", sa.String(64), nullable=False),
        sa.Column("parent_checkpoint_id", sa.String(64), nullable=True),
        sa.Column("checkpoint_type", sa.String(32), nullable=False),
        sa.Column("checkpoint", sa.LargeBinary, nullable=False),
        sa.Column("metadata_type", sa.String(32), nullable=False),
        sa.Column("metadata_blob", sa.LargeBinary, nullable=False),
        sa.Column("created_at", sa.DateTime, nullable=False),
        sa.PrimaryKeyConstraint("thread_id", "checkpoint_ns", "checkpoint_id"),
    )
    # The idle-conversation sweep groups by thread and reads created_at.
    op.create_index("ix_lg_checkpoints_thread_created", "lg_checkpoints", ["thread_id", "created_at"])
    op.create_table(
        "lg_checkpoint_writes",
        sa.Column("thread_id", sa.String(255), nullable=False),
        sa.Column("checkpoint_ns", sa.String(255), nullable=False, server_default=""),
        sa.Column("checkpoint_id", sa.String(64), nullable=False),
        sa.Column("task_id", sa.String(64), nullable=False),
        sa.Column("idx", sa.Integer, nullable=False),
        sa.Column("channel", sa.String(255), nullable=False),
        sa.Column("value_type", sa.String(32), nullable=False),
        sa.Column("value", sa.LargeBinary, nullable=False),
        sa.Column("task_path", sa.String(255), nullable=False, server_default=""),
        sa.PrimaryKeyConstraint("thread_id", "checkpoint_ns", "checkpoint_id", "task_id", "idx"),
    )


def downgrade() -> None:
    op.drop_table("lg_checkpoint_writes")
    op.drop_index("ix_lg_checkpoints_thread_created", table_name="lg_checkpoints")
    op.drop_table("lg_checkpoints")
