# Copyright (c) 2025 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.

"""Management utility for VM Migration Scheduler."""

import sys
import os
from oslo_config import cfg
from oslo_log import log as logging

from vmms import config

def do_db_sync():
    """Sync the database up to the most recent version."""
    # Set up migration configuration
    import alembic.config
    
    # Get the absolute path to alembic.ini
    alembic_ini_path = os.path.join(
        os.path.dirname(__file__), 
        '..', 'db', 'sqlalchemy', 'alembic', 'alembic.ini'
    )
    alembic_ini_path = os.path.abspath(alembic_ini_path)
    
    # Use alembic directly
    alembic_cfg = alembic.config.Config(alembic_ini_path)
    
    # Get database connection from config
    CONF = cfg.CONF
    db_connection = CONF.database.connection
    
    # Set the database URL in alembic config
    alembic_cfg.set_main_option("sqlalchemy.url", db_connection)
    
    alembic.command.upgrade(alembic_cfg, 'head')
    
    LOG = logging.getLogger(__name__)
    LOG.info("Database sync completed successfully")

def add_command_parsers(subparsers):
    CommandParser = subparsers.add_parser
    parser = CommandParser('db_sync', help='Sync the database up to the most recent version.')
    parser.set_defaults(func=do_db_sync)

def main():
    """Parse options and call the appropriate class/method."""
    # Create CONF object first
    CONF = cfg.CONF
    
    # Register CLI options before parsing
    CONF.register_cli_opts([
        cfg.SubCommandOpt('command',
                          title='Commands',
                          help='Available commands',
                          handler=add_command_parsers)
    ])
    
    # Initialize config with the CONF object that already has CLI options
    CONF = config.init_config(conf=CONF)
    logging.setup(CONF, 'vmms-manage')
    
    # Parse command line arguments
    CONF(sys.argv[1:], project='vmms')
    
    # Execute the command
    if hasattr(CONF.command, 'func'):
        CONF.command.func()
    else:
        print("No valid command specified. Use --help for usage.")
        sys.exit(1)
