import logging
from sqlalchemy import *

from rhodecode.lib.dbmigrate.versions import _reset_base
from rhodecode.model import meta, init_model_encryption


log = logging.getLogger(__name__)


def upgrade(migrate_engine):
    """
    Upgrade operations go here.
    Don't create your own engine; bind migrate_engine to your metadata
    """
    _reset_base(migrate_engine)

    from rhodecode.lib.dbmigrate.schema import db_4_20_0_1 as db

    init_model_encryption(db)

    # Add default PR target branch pre-population setting
    fixups(db, meta.Session)


def downgrade(migrate_engine):
    pass


def fixups(models, _SESSION):
    def get_by_name(cls, key):
        return cls.query().filter(cls.app_settings_name == key).scalar()

    def create_or_update(cls, key, val="True", type_="bool"):
        res = get_by_name(cls, key)
        if not res:
            res = cls(key, val, type_)
            print(f"Creating new setting: {key} = {val}")
        else:
            print(f"Setting {key} already exists, skipping")
        return res

    # Add global default setting
    setting_name = "pr_target_branch_prepopulate"
    setting_value = "True"  # Default to True to maintain existing behavior
    setting_type = "bool"

    sett = create_or_update(models.RhodeCodeSetting, setting_name, setting_value, setting_type)
    _SESSION().add(sett)
    _SESSION().commit()
