"""Add flattened tool persistence columns to skills table.

Adds columns for caching flattened tool sets, includes, capability
summaries, original YAML text, and a SHA-256 hash for refresh
invalidation.  Also adds a uniqueness constraint on the ``name``
column (defence-in-depth — already PK-unique) and ensures the
``ix_skills_namespace`` index exists for filtered listing.

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

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

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


def upgrade() -> None:
    """Add flattened tool caching columns to skills table."""
    with op.batch_alter_table("skills") as batch_op:
        batch_op.add_column(
            sa.Column("flattened_tools_json", sa.Text(), nullable=True),
        )
        batch_op.add_column(
            sa.Column("includes_json", sa.Text(), nullable=True),
        )
        batch_op.add_column(
            sa.Column("capability_summary_json", sa.Text(), nullable=True),
        )
        batch_op.add_column(
            sa.Column("yaml_text", sa.Text(), nullable=True),
        )
        batch_op.add_column(
            sa.Column("flattening_hash", sa.String(64), nullable=True),
        )
        # Defence-in-depth: explicit uniqueness on name (already PK).
        batch_op.create_unique_constraint(
            "uq_skills_name",
            ["name"],
        )


def downgrade() -> None:
    """Remove flattened tool caching columns from skills table."""
    with op.batch_alter_table("skills") as batch_op:
        batch_op.drop_constraint("uq_skills_name", type_="unique")
        batch_op.drop_column("flattening_hash")
        batch_op.drop_column("yaml_text")
        batch_op.drop_column("capability_summary_json")
        batch_op.drop_column("includes_json")
        batch_op.drop_column("flattened_tools_json")
