"""Create checkpoint_metadata table.

Adds the ``checkpoint_metadata`` table for Stage M6 (checkpointing and
rollback).  The table stores sandbox snapshot metadata aligned to the
specification schema: ULID primary key, owning plan reference, optional
decision and resource references, checkpoint type, filesystem path,
size, creation timestamp, and a JSON audit metadata blob.

Revision ID: m6_001_checkpoint_metadata
Revises: m4_002_skill_flattened_tools
Create Date: 2026-02-26 00:00:00

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

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


def upgrade() -> None:
    """Create checkpoint_metadata table."""

    op.create_table(
        "checkpoint_metadata",
        sa.Column("checkpoint_id", sa.String(26), primary_key=True),
        sa.Column(
            "plan_id",
            sa.String(26),
            sa.ForeignKey("v3_plans.plan_id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("decision_id", sa.String(26), nullable=True),
        sa.Column(
            "checkpoint_type", sa.Text(), nullable=False, server_default="manual"
        ),
        sa.Column("resource_id", sa.String(26), nullable=True),
        sa.Column("sandbox_ref", sa.Text(), nullable=False),
        sa.Column("filesystem_path", sa.Text(), nullable=False, server_default=""),
        sa.Column("size_bytes", sa.Integer(), nullable=True),
        sa.Column("created_at", sa.String(30), nullable=False),
        sa.Column("metadata_json", sa.Text(), nullable=True),
    )

    op.create_index(
        "idx_checkpoints_plan",
        "checkpoint_metadata",
        ["plan_id"],
    )
    op.create_index(
        "ix_checkpoint_metadata_created_at",
        "checkpoint_metadata",
        ["created_at"],
    )


def downgrade() -> None:
    """Drop checkpoint_metadata table."""

    op.drop_index("ix_checkpoint_metadata_created_at", table_name="checkpoint_metadata")
    op.drop_index("idx_checkpoints_plan", table_name="checkpoint_metadata")
    op.drop_table("checkpoint_metadata")
