# Copyright (C) 2010-2024 RhodeCode GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# (only), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# This program is dual-licensed. If you wish to learn more about the
# RhodeCode Enterprise Edition, including its added features, Support services,
# and proprietary license terms, please see https://rhodecode.com/licenses/

import time
import logging

from rhodecode.config.settings_maker import initialize_ini_config_default_values_if_not_present, generate_token
from rhodecode.lib.config_utils import get_app_config_lightweight

from rhodecode.lib.hook_daemon.base import Hooks
from rhodecode.lib.hook_daemon.hook_module import HooksModuleCallbackDaemon
from rhodecode.lib.hook_daemon.celery_hooks_deamon import CeleryHooksCallbackDaemon
from rhodecode.lib.type_utils import str2bool

log = logging.getLogger(__name__)


def prepare_callback_daemon(extras, protocol: str, txn_id=None):
    hooks_config = {}
    match protocol:
        case "celery":
            initialize_ini_config_default_values_if_not_present(
                ini_path=extras["config"], option="app.service_api.token", default_val=generate_token()
            )
            config = get_app_config_lightweight(extras["config"])

            broker_url = config.get("celery.broker_url")
            result_backend = config.get("celery.result_backend")

            hooks_config = {
                "broker_url": broker_url,
                "result_backend": result_backend,
            }

            callback_daemon = CeleryHooksCallbackDaemon(broker_url, result_backend)
        case "local":
            callback_daemon = HooksModuleCallbackDaemon(Hooks.__module__)
        case _:
            log.error('Unsupported callback daemon protocol "%s"', protocol)
            raise Exception("Unsupported callback daemon protocol.")

    extras["hooks_config"] = hooks_config
    extras["hooks_protocol"] = protocol
    extras["time"] = time.time()

    # register txn_id
    extras["txn_id"] = txn_id
    log.debug("Prepared a callback daemon: %s", callback_daemon.__class__.__name__)
    return callback_daemon, extras
