# FlightMonitor/__main__.py
import tkinter as tk

# MODIFIED: Import the logging configuration dictionary
# WHY: Need to pass configuration to the logger setup function.
# HOW: Added import.
from .data.logging_config import LOGGING_CONFIG  # Import the config dictionary

# MODIFIED: Import the new setup_basic_logging function AND get_logger function
# WHY: Need to call the centralized basic setup function early and get logger instances.
# HOW: Changed setup_logging to setup_basic_logging.
from .utils.logger import setup_basic_logging, get_logger  # MODIFIED HERE

from .gui.main_window import MainWindow
from .controller.app_controller import AppController


def main():
    """
    Main function to launch the Flight Monitor application.
    Initializes the Tkinter root, sets up basic logging, creates the controller
    and the main window, and starts the event loop.
    """
    # Initialize the Tkinter root window FIRST
    root = tk.Tk()

    # MODIFIED: Setup basic logging AFTER Tkinter root is created
    # WHY: The Tkinter-based log processor needs a root instance to schedule itself.
    #      The TkinterTextHandler itself will be added later by MainWindow.
    # HOW: Called setup_basic_logging here, passing the necessary arguments.
    setup_basic_logging(  # MODIFIED HERE
        root_tk_instance_for_processor=root,  # MODIFIED: Pass root for the log processor
        logging_config_dict=LOGGING_CONFIG,
    )

    # Now that basic logging is set up (console, file, queue), we can use module_logger
    module_logger_main = get_logger(__name__)
    module_logger_main.info("Application starting...")

    # Create the application controller
    app_controller = AppController()

    # Create the main application window
    # MainWindow itself will now handle the creation and specific addition of its log widget
    # to the logging system using a new dedicated function in the logger module.
    main_app_window = MainWindow(root, app_controller)

    # Set the main window instance in the controller
    app_controller.set_main_window(main_app_window)

    # Start the Tkinter event loop
    module_logger_main.info("Starting Tkinter main loop.")
    root.mainloop()
    module_logger_main.info("Tkinter main loop finished.")

    # Cleanup is handled by MainWindow's _on_closing method, which in turn
    # calls controller.on_application_exit and logger.shutdown_logging_system.
    module_logger_main.info("Application finished.")


if __name__ == "__main__":
    main()
