"""add cancel and streaming columns"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect

revision = '2a40df941760'
down_revision = 'c65ec0e3284a'
branch_labels = None
depends_on = None


def upgrade() -> None:
    conn = op.get_bind()
    inspector = inspect(conn)

    columns = [col['name'] for col in inspector.get_columns('transkripsi_tasks')]
    indexes = [idx['name'] for idx in inspector.get_indexes('transkripsi_tasks')]

    # partial_result
    if 'partial_result' not in columns:
        op.add_column(
            'transkripsi_tasks',
            sa.Column('partial_result', sa.Text(), nullable=True)
        )

    # segments_json
    if 'segments_json' not in columns:
        op.add_column(
            'transkripsi_tasks',
            sa.Column('segments_json', sa.Text(), nullable=True)
        )

    # is_cancelled (SQLite-safe)
    if 'is_cancelled' not in columns:
        op.add_column(
            'transkripsi_tasks',
            sa.Column(
                'is_cancelled',
                sa.Boolean(),
                nullable=False,
                server_default='0'
            )
        )

    # index
    if 'ix_transkripsi_tasks_user_id' not in indexes:
        op.create_index(
            'ix_transkripsi_tasks_user_id',
            'transkripsi_tasks',
            ['user_id'],
            unique=False
        )

    # ❌ SKIP FOREIGN KEY (SQLite tidak support ALTER constraint)
    # Kalau nanti pindah ke PostgreSQL baru aktifkan


def downgrade() -> None:
    conn = op.get_bind()
    inspector = inspect(conn)

    indexes = [idx['name'] for idx in inspector.get_indexes('transkripsi_tasks')]
    columns = [col['name'] for col in inspector.get_columns('transkripsi_tasks')]

    if 'ix_transkripsi_tasks_user_id' in indexes:
        op.drop_index('ix_transkripsi_tasks_user_id', table_name='transkripsi_tasks')

    # ⚠️ SQLite: drop column tidak selalu aman → optional
    # uncomment kalau benar-benar perlu dan DB masih kecil

    # if 'is_cancelled' in columns:
    #     op.drop_column('transkripsi_tasks', 'is_cancelled')

    # if 'segments_json' in columns:
    #     op.drop_column('transkripsi_tasks', 'segments_json')

    # if 'partial_result' in columns:
    #     op.drop_column('transkripsi_tasks', 'partial_result')