"""set agent_resources used column not null with default 0

Revision ID: 321c033a321b
Revises: acd2e76c1e40
Create Date: 2026-02-10 09:14:41.686614

"""

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "321c033a321b"
down_revision = "acd2e76c1e40"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Backfill existing NULLs before adding NOT NULL constraint
    op.execute("UPDATE agent_resources SET used = 0 WHERE used IS NULL")
    op.alter_column(
        "agent_resources",
        "used",
        existing_type=sa.NUMERIC(precision=24, scale=6),
        nullable=False,
        server_default=sa.text("0"),
    )
    op.add_column(
        "resource_allocations", sa.Column("free_at", sa.DateTime(timezone=True), nullable=True)
    )
    op.create_index(
        "ix_ra_occupied",
        "resource_allocations",
        ["kernel_id", "slot_name"],
        unique=False,
        postgresql_where=sa.text("free_at IS NULL"),
    )


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(
        "ix_ra_occupied",
        table_name="resource_allocations",
        postgresql_where=sa.text("free_at IS NULL"),
    )
    op.drop_column("resource_allocations", "free_at")
    op.alter_column(
        "agent_resources",
        "used",
        existing_type=sa.NUMERIC(precision=24, scale=6),
        nullable=True,
        server_default=None,
    )
    # ### end Alembic commands ###
