from core.configuration.feature_flags import FeatureFlags
from core.configuration.feature_flags_enum import FeatureFlagsEnum
from core.logger import DBLogger
from data.abc.data_seeder_abc import DataSeederABC
from data.schemas.system.feature_flag import FeatureFlag
from data.schemas.system.feature_flag_dao import featureFlagDao

logger = DBLogger(__name__)


class FeatureFlagsSeeder(DataSeederABC):
    def __init__(self):
        DataSeederABC.__init__(self)

    async def seed(self):
        logger.info("Seeding feature flags")
        feature_flags = await featureFlagDao.get_all()
        feature_flag_keys = [x.key for x in feature_flags]

        possible_feature_flags = {
            x.value: FeatureFlags.get_default(x) for x in FeatureFlagsEnum
        }

        # Create new feature flags
        to_create = [
            FeatureFlag(0, x, possible_feature_flags[x])
            for x in possible_feature_flags.keys()
            if x not in feature_flag_keys
        ]
        if len(to_create) > 0:
            await featureFlagDao.create_many(to_create)
            to_create_dicts = {x.key: x.value for x in to_create}
            logger.debug(f"Created feature flags: {to_create_dicts}")

        # Update existing feature flags if they can be overwritten and have a different value
        to_update = [
            FeatureFlag(x.id, x.key, possible_feature_flags[x.key])
            for x in feature_flags
            if FeatureFlags.overwrite_flag(x.key)
            and x.value != possible_feature_flags[x.key]
        ]
        if len(to_update) > 0:
            await featureFlagDao.update_many(to_update)
            to_update_dicts = {x.key: x.value for x in to_update}
            logger.debug(f"Updated feature flags: {to_update_dicts}")

        # Delete feature flags that are no longer defined
        to_delete = [
            x for x in feature_flags if x.key not in possible_feature_flags.keys()
        ]
        if len(to_delete) > 0:
            await featureFlagDao.delete_many(to_delete, hard_delete=True)
            to_delete_dicts = {x.key: x.value for x in to_delete}
            logger.debug(f"Deleted feature flags: {to_delete_dicts}")
