"""add persistent post-stop gate-reset observation

Revision ID: 022
Revises: 021
Create Date: 2026-07-17 00:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "022"
down_revision: Union[str, None] = "021"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column(
        "paper_trades",
        sa.Column("reentry_gate_failed_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.add_column(
        "paper_trades",
        sa.Column(
            "reentry_gate_requalified_at",
            sa.DateTime(timezone=True),
            nullable=True,
        ),
    )
    # The policy starts at this deployment. Historical NULL values mean the
    # scanner never recorded reset observations, not that those old episodes
    # are still active. Mark both transitions complete so only stops created
    # after the migration can open a re-entry lock.
    op.execute(
        sa.text(
            """
            UPDATE paper_trades
            SET reentry_gate_failed_at = closed_at,
                reentry_gate_requalified_at = closed_at
            WHERE status = 'closed'
              AND close_reason = 'stop'
              AND closed_at IS NOT NULL
            """
        )
    )


def downgrade() -> None:
    op.drop_column("paper_trades", "reentry_gate_requalified_at")
    op.drop_column("paper_trades", "reentry_gate_failed_at")
