import argparse
import logging
from argparse import Namespace

from .fatal_handling import tomte_exit
from .migrations import execute_migrations, is_migration_needed
from .state_manager import reset_installed_state

logger = logging.getLogger(__name__)
startup_logger = logging.getLogger(f"{__name__.split('.', 1)[0]}.startup")


def parse_args() -> Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--reset", action="store_true", help="Delete all stored installation flags"
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Delete all stored installation flags and start",
    )
    parser.add_argument(
        "--migrate",
        action="store_true",
        help="Execute migrations from older versions",
    )
    args = parser.parse_args()
    startup_logger.info(
        "Started tuxedo-tomte with args: %s",
        " ".join(f"{k}={v}" for k, v in vars(args).items()),
    )

    return args


def run_flag_commands_and_maybe_exit(args: Namespace) -> None:
    """Executes flag commands and exits if necessary."""
    if args.reset or args.force:
        logger.info("Resetting installation state...")

        # exit on failure
        if not reset_installed_state():
            tomte_exit(1)

        # exit only on reset and not on force
        if args.reset:
            tomte_exit(0)

    if args.migrate:
        logger.info("Migrating installation state...")
        if not is_migration_needed():
            logger.info("No migration needed.")
            tomte_exit(0)
        if not execute_migrations():
            logger.error("Migration failed.")
            tomte_exit(1)
        tomte_exit(0)

    if is_migration_needed():
        execute_migrations()
