"""Add exiled games and skip_exile consumable

Revision ID: 030
Revises: 029
Create Date: 2025-01-10
"""
from alembic import op
from sqlalchemy import inspect
import sqlalchemy as sa


revision = '031_add_exiled_games'
down_revision = '030_merge_029_heads'
branch_labels = None
depends_on = None


def table_exists(table_name: str) -> bool:
    bind = op.get_bind()
    inspector = inspect(bind)
    return table_name in inspector.get_table_names()


def upgrade():
    # Create exiled_games table if not exists
    if not table_exists('exiled_games'):
        op.create_table(
            'exiled_games',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('participant_id', sa.Integer(), nullable=False),
            sa.Column('game_id', sa.Integer(), nullable=False),
            sa.Column('assignment_id', sa.Integer(), nullable=True),
            sa.Column('exiled_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
            sa.Column('exiled_by', sa.String(20), nullable=False),
            sa.Column('reason', sa.String(500), nullable=True),
            sa.Column('is_active', sa.Boolean(), nullable=False, server_default='true'),
            sa.Column('unexiled_at', sa.DateTime(), nullable=True),
            sa.Column('unexiled_by', sa.String(20), nullable=True),
            sa.PrimaryKeyConstraint('id'),
            sa.ForeignKeyConstraint(['participant_id'], ['participants.id'], ondelete='CASCADE'),
            sa.ForeignKeyConstraint(['game_id'], ['games.id'], ondelete='CASCADE'),
            sa.ForeignKeyConstraint(['assignment_id'], ['assignments.id'], ondelete='SET NULL'),
            sa.UniqueConstraint('participant_id', 'game_id', name='unique_participant_game_exile'),
        )
        op.create_index('ix_exiled_games_participant_id', 'exiled_games', ['participant_id'])
        op.create_index('ix_exiled_games_active', 'exiled_games', ['participant_id', 'is_active'])

    # Add skip_exile consumable to shop if not exists
    op.execute("""
        INSERT INTO shop_items (item_type, code, name, description, price, rarity, asset_data, is_active, created_at)
        SELECT 'consumable', 'skip_exile', 'Скип с изгнанием',
               'Пропустить текущее задание без штрафа. Игра навсегда исключается из вашего пула и больше не выпадет.',
               150, 'rare', '{"effect": "skip_exile", "icon": "x-circle"}', true, NOW()
        WHERE NOT EXISTS (SELECT 1 FROM shop_items WHERE code = 'skip_exile')
    """)


def downgrade():
    # Remove skip_exile from shop
    op.execute("DELETE FROM shop_items WHERE code = 'skip_exile'")

    # Drop exiled_games table
    op.drop_index('ix_exiled_games_active', table_name='exiled_games')
    op.drop_index('ix_exiled_games_participant_id', table_name='exiled_games')
    op.drop_table('exiled_games')
