"""drop satbots table

Revision ID: f1a4ec5e34e5
Revises: fed7415a80da
Create Date: 2026-01-16 10:29:24.933061

"""
import os
from alembic import op, context
import sqlalchemy as sa

from setup import CONFIG
from main.services.custom_sqlalchemy_types import EnumSqlalchemyType
from main.services.satbots.satbot_priority import SatbotPriority
from main.services.satbots.satbot_state import SatbotState
from main.services.satbots.satbot_type import SatbotType


# revision identifiers, used by Alembic.
revision = 'f1a4ec5e34e5'
down_revision = 'fed7415a80da'
branch_labels = None
depends_on = None


def upgrade():
    database = context.get_context().connection.engine.url.database
    op.execute(sa.text(f"COPY satbots TO '{CONFIG['satbots']['backups_directory']}/{database}_satbots.csv' (FORMAT CSV)"))
    op.drop_constraint('alerts_satbot_id_fkey', 'alerts')
    op.drop_constraint('orders_satbot_id_fkey', 'orders')
    op.drop_table('satbots')


def downgrade():
    op.create_table('satbots',
        sa.Column('id', sa.Integer(), nullable=False, autoincrement=True),
        sa.Column('type', EnumSqlalchemyType(SatbotType), nullable=False),
        sa.Column('state', EnumSqlalchemyType(SatbotState), nullable=False),
        sa.Column('progress', sa.Integer(), nullable=True),
        sa.Column('pid', sa.Integer(), nullable=True),
        sa.Column('priority', EnumSqlalchemyType(SatbotPriority), nullable=True),
        sa.Column('log', sa.ARRAY(sa.String()), nullable=True),
        sa.Column('created_at', sa.TIMESTAMP(), server_default=sa.text("TIMEZONE('utc', CURRENT_TIMESTAMP)"), nullable=False),
        sa.Column('created_by_id', sa.Integer(), nullable=True),
        sa.Column('started_at', sa.TIMESTAMP(), nullable=True),
        sa.Column('finished_at', sa.TIMESTAMP(), nullable=True),
        sa.Column('parameters', sa.JSON(), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )
    
    database = context.get_context().connection.engine.url.database
    if os.path.exists(os.path.join(CONFIG['satbots']['backups_directory'], f"{database}_satbots.csv")):
        op.execute(sa.text(f"COPY satbots FROM '{CONFIG['satbots']['backups_directory']}/{database}_satbots.csv' (FORMAT CSV)"))

    op.create_foreign_key('alerts_satbot_id_fkey', 'alerts', 'satbots', ['satbot_id'], ['id'])
    op.create_foreign_key('orders_satbot_id_fkey', 'orders', 'satbots', ['satbot_id'], ['id'])
