from sqlalchemy import inspect, text


def applyMigration(databaseContext):
    engine = databaseContext['engine']
    inspector = inspect(engine)
    shiftedSeasonColumns = {
        column['name']
        for column in inspector.get_columns('shifted_seasons')
    }
    showColumns = {
        column['name']
        for column in inspector.get_columns('shows')
    }

    with engine.begin() as connection:
        if 'pattern_id' not in shiftedSeasonColumns:
            connection.execute(text("PRAGMA foreign_keys=OFF"))
            connection.execute(
                text(
                    """
                    CREATE TABLE shifted_seasons_v3 (
                        id INTEGER PRIMARY KEY,
                        show_id INTEGER,
                        pattern_id INTEGER,
                        original_season INTEGER,
                        first_episode INTEGER DEFAULT -1,
                        last_episode INTEGER DEFAULT -1,
                        season_offset INTEGER DEFAULT 0,
                        episode_offset INTEGER DEFAULT 0,
                        FOREIGN KEY(show_id) REFERENCES shows(id) ON DELETE CASCADE,
                        FOREIGN KEY(pattern_id) REFERENCES patterns(id) ON DELETE CASCADE,
                        CHECK (
                            (show_id IS NOT NULL AND pattern_id IS NULL)
                            OR (show_id IS NULL AND pattern_id IS NOT NULL)
                        )
                    )
                    """
                )
            )
            connection.execute(
                text(
                    """
                    INSERT INTO shifted_seasons_v3 (
                        id,
                        show_id,
                        pattern_id,
                        original_season,
                        first_episode,
                        last_episode,
                        season_offset,
                        episode_offset
                    )
                    SELECT
                        id,
                        show_id,
                        NULL,
                        original_season,
                        first_episode,
                        last_episode,
                        season_offset,
                        episode_offset
                    FROM shifted_seasons
                    """
                )
            )
            connection.execute(text("DROP TABLE shifted_seasons"))
            connection.execute(text("ALTER TABLE shifted_seasons_v3 RENAME TO shifted_seasons"))
            connection.execute(
                text("CREATE INDEX ix_shifted_seasons_show_id ON shifted_seasons(show_id)")
            )
            connection.execute(
                text("CREATE INDEX ix_shifted_seasons_pattern_id ON shifted_seasons(pattern_id)")
            )
            connection.execute(text("PRAGMA foreign_keys=ON"))

        if 'quality' not in showColumns:
            connection.execute(
                text("ALTER TABLE shows ADD COLUMN quality INTEGER DEFAULT 0")
            )
        if 'notes' not in showColumns:
            connection.execute(
                text("ALTER TABLE shows ADD COLUMN notes TEXT DEFAULT ''")
            )
