"""add fix outcome tracking columns to session_suggested_fixes

Adds: status, applied_at, verified_at, partial_notes, failure_reason,
ai_outcome_proposal.

status is the outcome dimension (did the fix work?), orthogonal to the
existing user_decision column (which script-path the engineer took).

Revision ID: 6492ec8d2d5b
Revises: f07010f17b01
Create Date: 2026-04-23 18:32:38.609719

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


# revision identifiers, used by Alembic.
revision: str = '6492ec8d2d5b'
down_revision: Union[str, None] = 'f07010f17b01'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column(
        "session_suggested_fixes",
        sa.Column("status", sa.String(length=20), nullable=False, server_default=sa.text("'proposed'")),
    )
    op.add_column(
        "session_suggested_fixes",
        sa.Column("applied_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.add_column(
        "session_suggested_fixes",
        sa.Column("verified_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.add_column(
        "session_suggested_fixes",
        sa.Column("partial_notes", sa.Text(), nullable=True),
    )
    op.add_column(
        "session_suggested_fixes",
        sa.Column("failure_reason", sa.Text(), nullable=True),
    )
    op.add_column(
        "session_suggested_fixes",
        sa.Column("ai_outcome_proposal", postgresql.JSONB(), nullable=True),
    )
    # Backfill before constraint creation so dismissed rows satisfy the new CHECK.
    op.execute(
        "UPDATE session_suggested_fixes "
        "SET status = 'dismissed' "
        "WHERE user_decision = 'dismissed'"
    )
    op.create_check_constraint(
        "ck_session_suggested_fixes_status",
        "session_suggested_fixes",
        "status IN ('proposed', 'applied_success', 'applied_failed', 'applied_partial', 'dismissed')",
    )
    op.alter_column("session_suggested_fixes", "status", server_default=None)


def downgrade() -> None:
    op.drop_constraint("ck_session_suggested_fixes_status", "session_suggested_fixes", type_="check")
    op.drop_column("session_suggested_fixes", "ai_outcome_proposal")
    op.drop_column("session_suggested_fixes", "failure_reason")
    op.drop_column("session_suggested_fixes", "partial_notes")
    op.drop_column("session_suggested_fixes", "verified_at")
    op.drop_column("session_suggested_fixes", "applied_at")
    op.drop_column("session_suggested_fixes", "status")
