"""remove satbot jwt

Revision ID: fed7415a80da
Revises: 9e43d8bea8c8
Create Date: 2025-11-07 14:46:58.776815

"""
from alembic import op
import sqlalchemy as sa
from setup import CONFIG
import jwt, json


# revision identifiers, used by Alembic.
revision = 'fed7415a80da'
down_revision = '9e43d8bea8c8'
branch_labels = None
depends_on = None
BATCH_SIZE = 10

def _parameters(satbot):
    parameters = jwt.decode(satbot.parameters, key=CONFIG['satbots']['jwt_secret'], algorithms=['HS256', ''])
    for key in ['update_displacements', '--dates']:
        if parameters.get(key):
            parameters[key] = [int(x) for x in parameters[key].replace("'", '').split(',')]
    return json.dumps(parameters)

def upgrade():
    users_connection = op.get_bind()

    op.add_column('satbots', sa.Column('params', sa.JSON()))

    satbot_ids = users_connection.execute(sa.text("SELECT id FROM satbots")).fetchall()
    satbot_ids = [x[0] for x in satbot_ids]

    for batch in range(0, len(satbot_ids), BATCH_SIZE):
        satbot_batch_ids = satbot_ids[batch:batch+BATCH_SIZE]
        queries = []
        satbots = users_connection.execute(sa.text(f"SELECT id, parameters FROM satbots WHERE id in ({','.join([str(x) for x in satbot_batch_ids])})")).fetchall()

        for satbot in satbots:
            queries.append(f"UPDATE satbots SET params = '{_parameters(satbot)}' WHERE id = {satbot.id}")

        users_connection.execute(sa.text(';'.join(queries)))

    op.drop_column('satbots', 'parameters')
    op.alter_column('satbots', 'params', new_column_name='parameters')


def downgrade():
    users_connection = op.get_bind()

    op.add_column('satbots', sa.Column('params', sa.String()))

    satbot_ids = users_connection.execute(sa.text("SELECT id FROM satbots")).fetchall()
    satbot_ids = [x[0] for x in satbot_ids]

    for batch in range(0, len(satbot_ids), BATCH_SIZE):
        satbot_batch_ids = satbot_ids[batch:batch+BATCH_SIZE]
        queries = []
        satbots = users_connection.execute(sa.text(f"SELECT id, parameters FROM satbots WHERE id in ({','.join([str(x) for x in satbot_batch_ids])})")).fetchall()

        for satbot in satbots:
            queries.append(f"UPDATE satbots SET params = '{jwt.encode(satbot.parameters, key=CONFIG['satbots']['jwt_secret'])}' WHERE id = {satbot.id}")

        users_connection.execute(sa.text(';'.join(queries)))

    op.drop_column('satbots', 'parameters')
    op.alter_column('satbots', 'params', new_column_name='parameters')
    