"""
Main entry point for the Radar Data Reader application.
"""

import tkinter as tk
import logging
from pathlib import Path

from radar_data_reader.gui.main_window import MainWindow
from radar_data_reader.gui.gui_utils import center_window
from radar_data_reader.utils import logger
from radar_data_reader.utils.config_manager import ConfigManager
from radar_data_reader.core.app_controller import AppController

LOGGING_CONFIG = {
    "default_root_level": logging.DEBUG,
    "format": "%(asctime)s [%(levelname)-8s] %(name)-20s: %(message)s",
    "date_format": "%H:%M:%S",
    "enable_console": True,
    "enable_file": False,
    "file_path": "radar_reader.log",
    "colors": {
        logging.DEBUG: "gray",
        logging.INFO: "black",
        logging.WARNING: "orange",
        logging.ERROR: "red",
        logging.CRITICAL: "red",
    },
}

PROJECT_ROOT = Path(__file__).parent.parent
CONFIG_DIR = PROJECT_ROOT / "config"
CONFIG_FILE_PATH = CONFIG_DIR / "config.json"


def main():
    root = None
    try:
        config_manager = ConfigManager(CONFIG_FILE_PATH)
        config_manager.load_config()

        controller = AppController(config_manager)

        root = tk.Tk()
        # Hide the window initially to prevent flickering while it's being built
        root.withdraw()

        logger.setup_basic_logging(root, LOGGING_CONFIG)

        view = MainWindow(
            master=root, controller=controller, logging_config=LOGGING_CONFIG
        )

        controller.bind_view(view)

        # Center the main window on the screen before showing it
        center_window(root)

        view.mainloop()

    except Exception as e:
        log_or_print = (
            logger.get_logger(__name__) if logger._logging_system_active else print
        )
        if callable(log_or_print):
            log_or_print(f"A critical error occurred: {e}")
        else:
            log_or_print.critical(f"A critical error occurred: {e}", exc_info=True)

        if root:
            root.destroy()


if __name__ == "__main__":
    main()
