import logging

from .config_parser import get_config
from .hardware_parser import HardwareSpecs
from .script_manager import (
    manage_scripts,
)
from .fatal_handling import (
    tomte_exit,
    check_root_privileges,
    check_single_instance_lock,
    check_internet,
)
from .logging import setup_logging
from .package_manager import detect_package_manager
from .config_mapper import (
    get_hardware_config_dependent_packages,
    get_hardware_config_dependent_scripts,
)
from .update_hardware_information import update_hardware_information
from .args_management import parse_args, run_flag_commands_and_maybe_exit
from .state_manager import ensure_installed_state_dirs

logger = logging.getLogger(__name__)


def main() -> None:
    check_root_privileges()
    setup_logging()

    args = parse_args()
    ensure_installed_state_dirs()
    check_single_instance_lock()
    run_flag_commands_and_maybe_exit(args)
    check_internet()

    logger.info("Updating Hardware Information…")
    update_hardware_information()
    logger.info("Updated Hardware Information")

    pm = detect_package_manager()
    if not pm:
        logger.fatal("Cannot find usable package manager. Exiting.")
        tomte_exit(1)
    logger.info(f"Using package manager: {pm.__class__.__name__}")

    logger.info("Evaluating configuration rules…")
    hardware_specs = HardwareSpecs()
    config = get_config()

    pkgs: set[str] = get_hardware_config_dependent_packages(hardware_specs, config)
    pm.manage_packages(pkgs)

    scripts: set[str] = get_hardware_config_dependent_scripts(hardware_specs, config)
    manage_scripts(scripts, pm.BIN)

    logger.info("All done.")


if __name__ == "__main__":
    main()
    tomte_exit(0)
