# SPDX-License-Identifier: Apache-2.0

import copy
from celery import Celery
from celery.signals import worker_process_init

from osism import utils
from osism.tasks import Config
from osism.tasks.conductor.config import get_configuration
from osism.tasks.conductor.ironic import sync_ironic as _sync_ironic
from osism.tasks.conductor.redfish import get_resources as _get_redfish_resources
from osism.tasks.conductor.sonic import sync_sonic as _sync_sonic
from osism.tasks.conductor.sonic import get_devices as _get_sonic_devices


# App configuration
app = Celery("conductor")
app.config_from_object(Config)


@worker_process_init.connect
def celery_init_worker(**kwargs):
    pass


@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    pass


# Tasks
@app.task(bind=True, name="osism.tasks.conductor.get_ironic_parameters")
def get_ironic_parameters(self):
    configuration = get_configuration()
    if "ironic_parameters" in configuration:
        # NOTE: Do not pass by reference, everybody gets their own copy to work with
        return copy.deepcopy(configuration["ironic_parameters"])

    return {}


@app.task(bind=True, name="osism.tasks.conductor.sync_netbox")
def sync_netbox(self, node_name=None, netbox_filter=None):
    # Check if tasks are locked before execution
    utils.check_task_lock_and_exit()

    from osism.tasks.conductor.ironic import sync_netbox_from_ironic

    sync_netbox_from_ironic(self.request.id, node_name, netbox_filter)


@app.task(bind=True, name="osism.tasks.conductor.sync_ironic")
def sync_ironic(
    self,
    node_name=None,
    force=False,
    dry_run=False,
    skip_kernel_params=None,
    extra_kernel_params=None,
):
    # Check if tasks are locked before execution
    utils.check_task_lock_and_exit()

    _sync_ironic(
        self.request.id,
        get_ironic_parameters,
        node_name,
        force,
        dry_run,
        skip_kernel_params=skip_kernel_params or [],
        extra_kernel_params=extra_kernel_params or [],
    )


@app.task(bind=True, name="osism.tasks.conductor.sync_sonic")
def sync_sonic(self, device_name=None, show_diff=True):
    # Check if tasks are locked before execution
    utils.check_task_lock_and_exit()

    return _sync_sonic(device_name, self.request.id, show_diff)


@app.task(bind=True, name="osism.tasks.conductor.get_redfish_resources")
def get_redfish_resources(self, hostname, resource_type):
    return _get_redfish_resources(hostname, resource_type)


@app.task(bind=True, name="osism.tasks.conductor.get_sonic_devices")
def get_sonic_devices(self, device_name=None):
    return _get_sonic_devices(device_name)


__all__ = [
    "app",
    "get_ironic_parameters",
    "get_redfish_resources",
    "get_sonic_devices",
    "sync_netbox",
    "sync_ironic",
    "sync_sonic",
]
