# Copyright (c) 2026 Thomas Goirand <zigo@debian.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Command-line interface for starting the Vigie Worker daemon."""

import sys

from oslo_service.backend import init_backend, BackendType
init_backend(BackendType.THREADING)

from oslo_log import log as logging

from vigie import service
from vigie import rpc
from vigie.config import get_config

# Initialize configuration early so logging and options are available
CONF = get_config()

# Setup logging for the worker daemon
logging.setup(CONF, 'vigie-worker')
LOG = logging.getLogger(__name__)


def main():
    """Main entry point for the vigie-worker daemon.
    
    This function is called by the console_script entry point.
    It initializes the environment and starts the service loop.
    """
    try:
        # Initialize RPC transport (RabbitMQ, Kafka, etc.)
        # This must happen before creating the service so the manager can use RPC.
        rpc.init(CONF)

        LOG.info("Starting vigie-worker service...")

        # Create the Service wrapper instance.
        # - binary: The name of the executable (used for service records).
        # - manager: The dotted path to the Manager class implementing the logic.
        # - topic: The RPC topic this service will listen on.
        srv = service.Service.create(
            binary='vigie-worker',
            manager='vigie.worker.manager.WorkerManager',
            topic=f'vigie-worker.{CONF.worker.my_hostname}'
        )

        # Launch the service using oslo_service's ProcessLauncher.
        # This handles signal trapping, process forking (if workers > 1), and restarts.
        service.serve(srv)

        # 4. Wait for the service to finish (blocks until SIGTERM/SIGINT).
        service.wait()

    except Exception as e:
        LOG.critical(f"Failed to start vigie-worker: {e}", exc_info=True)
        sys.exit(1)
    finally:
        # Ensure RPC resources are cleaned up on exit
        rpc.cleanup()
        LOG.info("vigie-worker shutdown complete.")

if __name__ == '__main__':
    main()
