"""Hydrate DDR and Reflec Beat song DB for catalog BEMAPI support.

Revision ID: 36dff3ac15a3
Revises: a522b9e42df4
Create Date: 2019-12-07 03:39:55.137275

"""
import json
from alembic import op
from sqlalchemy.sql import text
from typing import Dict, Any


# revision identifiers, used by Alembic.
revision = '36dff3ac15a3'
down_revision = 'a522b9e42df4'
branch_labels = None
depends_on = None


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

    # Grab reflec beat LUT
    sql = "SELECT id, genre FROM music WHERE game = 'reflec' AND version = 0"
    results = conn.execute(text(sql), {})
    reflec_todo: Dict[int, str] = {}
    for result in results:
        reflec_todo[result['id']] = result['genre']

    # Now, hydrate the existing data
    sql = "SELECT id, version, data FROM music WHERE game = 'reflec'"
    results = conn.execute(text(sql), {})
    for result in results:
        data = json.loads(result['data'])
        data = {**data, 'chart_id': reflec_todo[result['id']]}

        sql = "UPDATE music SET data = :data WHERE game = 'reflec' AND id = :id AND version = :version"
        conn.execute(
            text(sql),
            {
                'data': json.dumps(data),
                'id': result['id'],
                'version': result['version'],
            }
        )

    # Grab DDR LUT
    sql = "SELECT id, songid, data FROM music WHERE game = 'ddr' AND version = 0"
    results = conn.execute(text(sql), {})
    for result in results:
        data = json.loads(result['data'])
        data = {**data, 'edit_id': result['songid']}

        sql = "UPDATE music SET data = :data WHERE game = 'ddr' AND id = :id"
        conn.execute(
            text(sql),
            {
                'data': json.dumps(data),
                'id': result['id'],
            }
        )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###
