"""Add ABANDONED to episode_outcome enum

Revision ID: 0006
Revises: 0005
Create Date: 2025-01-06

This migration adds the 'abandoned' value to the episode_outcome enum type.
This allows episodes to track when a task was abandoned (not completed,
but not necessarily a failure either - e.g., user cancelled, session timeout).
"""

from collections.abc import Sequence

from alembic import op

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


def upgrade() -> None:
    """Add 'abandoned' value to episode_outcome enum."""
    # PostgreSQL ALTER TYPE ADD VALUE is safe and non-blocking
    op.execute("ALTER TYPE episode_outcome ADD VALUE IF NOT EXISTS 'abandoned'")


def downgrade() -> None:
    """Remove 'abandoned' from episode_outcome enum.

    Note: PostgreSQL doesn't support removing values from enums directly.
    This downgrade converts any 'abandoned' episodes to 'failure' and
    recreates the enum without 'abandoned'.
    """
    # Convert any abandoned episodes to failure first
    op.execute("""
        UPDATE episodes
        SET outcome = 'failure'
        WHERE outcome = 'abandoned'
    """)

    # Recreate the enum without abandoned
    # This is complex in PostgreSQL - requires creating new type, updating columns, dropping old
    op.execute("ALTER TYPE episode_outcome RENAME TO episode_outcome_old")
    op.execute("CREATE TYPE episode_outcome AS ENUM ('success', 'failure', 'partial')")
    op.execute("""
        ALTER TABLE episodes
        ALTER COLUMN outcome TYPE episode_outcome
        USING outcome::text::episode_outcome
    """)
    op.execute("DROP TYPE episode_outcome_old")
