"""Add reversion_count, last_completed_step, last_checkpoint_id columns to v3_plans.

These columns are required for plan resume and reversion-limit functionality.
Without them, ``Plan.reversion_count``, ``last_completed_step``, and
``last_checkpoint_id`` are not persisted to the database, causing plan resume
and reversion limits to fail after a process restart.

Revision ID: m9_002_plan_resume_fields
Revises: m9_001_session_name_column
Create Date: 2026-04-05 00:00:00

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "m9_002_plan_resume_fields"
down_revision: str | Sequence[str] | None = "m9_001_session_name_column"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Add resume-tracking columns to ``v3_plans``.

    Adds ``reversion_count``, ``last_completed_step``, and
    ``last_checkpoint_id``.
    """
    op.add_column(
        "v3_plans",
        sa.Column(
            "reversion_count",
            sa.Integer(),
            nullable=False,
            server_default="0",
        ),
    )
    op.add_column(
        "v3_plans",
        sa.Column(
            "last_completed_step",
            sa.Integer(),
            nullable=False,
            server_default="-1",
        ),
    )
    op.add_column(
        "v3_plans",
        sa.Column("last_checkpoint_id", sa.Text(), nullable=True),
    )


def downgrade() -> None:
    """Remove resume-tracking columns from ``v3_plans``.

    Drops ``reversion_count``, ``last_completed_step``, and
    ``last_checkpoint_id``.
    """
    op.drop_column("v3_plans", "last_checkpoint_id")
    op.drop_column("v3_plans", "last_completed_step")
    op.drop_column("v3_plans", "reversion_count")
