# Path: dozer/db.py
# async def db_init(db_url):
#     """Initializes the database connection"""
#     global Pool
#     Pool = await asyncpg.create_pool(dsn=db_url, command_timeout=15)
# 
# async def db_migrate():
#     """Gets all subclasses and checks their migrations."""
#     async with Pool.acquire() as conn:
#         await conn.execute("""CREATE TABLE IF NOT EXISTS versions (
#         table_name text PRIMARY KEY,
#         version_num int NOT NULL
#         )""")
#     DOZER_LOGGER.info("Checking for db migrations")
#     for cls in DatabaseTable.__subclasses__():
#         exists = await Pool.fetchrow("""SELECT EXISTS(
#         SELECT 1
#         FROM information_schema.tables
#         WHERE
#         table_name = $1)""", cls.__tablename__)
#         if exists['exists']:
#             version = await Pool.fetchrow("""SELECT version_num FROM versions WHERE table_name = $1""", cls.__tablename__)
#             if version is None:
#                 # Migration/creation required, go to the function in the subclass for it
#                 await cls.initial_migrate()
#                 version = {"version_num": 0}
#             if int(version["version_num"]) < len(cls.__versions__):
#                 # the version in the DB is less than the version in the bot, run all the migrate scripts necessary
#                 DOZER_LOGGER.info(f"Table {cls.__tablename__} is out of date attempting to migrate")
#                 for i in range(int(version["version_num"]), len(cls.__versions__)):
#                     # Run the update script for this version!
#                     await cls.__versions__[i](cls)
#                     DOZER_LOGGER.info(f"Successfully updated table {cls.__tablename__} from version {i} to {i + 1}")
#                 async with Pool.acquire() as conn:
#                     await conn.execute("""UPDATE versions SET version_num = $1 WHERE table_name = $2""", len(cls.__versions__), cls.__tablename__)
#         else:
#             await cls.initial_create()
#             await cls.initial_migrate()


import json
import os
import sys
import asyncio
import discord
import sentry_sdk
from .db import db_init, db_migrate
from . import db
from . import Dozer  # After version check
    },
    'lavalink': {
        'enabled': False,
        'host': '127.0.0.1',
        'port': 2333,
        'password': 'youshallnotpass',
        'identifier': 'MAIN',
        'region': 'us_central'
    },
    'debug': False,
    'presences_intents': False,
    'is_backup': False,
    'invite_override': "",
    "sentry_url": ""
}
config_file = 'config.json'

if os.path.isfile(config_file):
    with open(config_file) as f:
        config.update(json.load(f))

with open('config.json', 'w') as f:
    json.dump(config, f, indent='\t')

if config['sentry_url'] != "":
    sentry_sdk.init(
        config['sentry_url'],
        traces_sample_rate=1.0,
    )


# Path: dozer/db.py
# async def db_init(db_url):
#     """Initializes the database connection"""
#     global Pool
#     Pool = await asyncpg.create_pool(dsn=db_url, command_timeout=15)
# 
# async def db_migrate():
#     """Gets all subclasses and checks their migrations."""
#     async with Pool.acquire() as conn:
#         await conn.execute("""CREATE TABLE IF NOT EXISTS versions (
#         table_name text PRIMARY KEY,
#         version_num int NOT NULL
#         )""")
#     DOZER_LOGGER.info("Checking for db migrations")
#     for cls in DatabaseTable.__subclasses__():
#         exists = await Pool.fetchrow("""SELECT EXISTS(
#         SELECT 1
#         FROM information_schema.tables
#         WHERE
#         table_name = $1)""", cls.__tablename__)
#         if exists['exists']:
#             version = await Pool.fetchrow("""SELECT version_num FROM versions WHERE table_name = $1""", cls.__tablename__)
#             if version is None:
#                 # Migration/creation required, go to the function in the subclass for it
#                 await cls.initial_migrate()
#                 version = {"version_num": 0}
#             if int(version["version_num"]) < len(cls.__versions__):
#                 # the version in the DB is less than the version in the bot, run all the migrate scripts necessary
#                 DOZER_LOGGER.info(f"Table {cls.__tablename__} is out of date attempting to migrate")
#                 for i in range(int(version["version_num"]), len(cls.__versions__)):
#                     # Run the update script for this version!
#                     await cls.__versions__[i](cls)
#                     DOZER_LOGGER.info(f"Successfully updated table {cls.__tablename__} from version {i} to {i + 1}")
#                 async with Pool.acquire() as conn:
#                     await conn.execute("""UPDATE versions SET version_num = $1 WHERE table_name = $2""", len(cls.__versions__), cls.__tablename__)
#         else:
#             await cls.initial_create()
#             await cls.initial_migrate()


# Path: dozer/__main__.py
import json
import os
import sys
import asyncio
import discord
import sentry_sdk
from .db import db_init, db_migrate
from . import db
from . import Dozer  # After version check

    },
    'lavalink': {
        'enabled': False,
        'host': '127.0.0.1',
        'port': 2333,
        'password': 'youshallnotpass',
        'identifier': 'MAIN',
        'region': 'us_central'
    },
    'debug': False,
    'presences_intents': False,
    'is_backup': False,
    'invite_override': "",
    "sentry_url": ""
}
config_file = 'config.json'

if os.path.isfile(config_file):
    with open(config_file) as f:
        config.update(json.load(f))

with open('config.json', 'w') as f:
    json.dump(config, f, indent='\t')

if config['sentry_url'] != "":
    sentry_sdk.init(
        config['sentry_url'],
        traces_sample_rate=1.0,
    )


asyncio.get_event_loop().run_until_complete(db_init(config['db_url']))