import tkinter as tk
import logging
import sys

# Import the necessary components from our application
from downloaderyoutube.gui.gui import App
from downloaderyoutube.utils.logger import setup_basic_logging, shutdown_logging_system

# --- Logging Configuration --
# This dictionary configures the logging system. It can be expanded later.
LOGGING_CONFIG = {
    "default_root_level": logging.DEBUG,
    "specific_levels": {
        # You can set different levels for different modules if needed
        # "pytube": logging.WARNING,
    },
    "format": "%(asctime)s [%(levelname)-8s] %(name)-25s : %(message)s",
    "date_format": "%Y-%m-%d %H:%M:%S",
    "enable_console": True,
    "enable_file": False,  # Set to True to enable file logging
    # "file_path": "downloader_app.log", # Uncomment if file logging is enabled
}

def main():
    """
    Application entry point.
    Initializes logging, creates the GUI, and starts the main loop.
    """
    # --- Diagnostic Prints ---
    print("-" * 50)
    print(f"--- PYTHON EXECUTABLE: {sys.executable}")
    

    root = tk.Tk()

    # --- Setup Logging ---
    # This is a crucial step to initialize the queue-based logging system.
    setup_basic_logging(
        root_tk_instance_for_processor=root, logging_config_dict=LOGGING_CONFIG
    )

    # Get a logger for the main entry point
    logger = logging.getLogger(__name__)
    logger.info("Application starting...")

    # --- Create and run the App ---
    app = App(master=root)

    def on_closing():
        """
        Handles the window closing event to ensure a clean shutdown.
        """
        logger.info("Shutdown sequence initiated.")
        # Properly shut down the logging system before closing the app
        shutdown_logging_system()
        root.destroy()

    # Assign the custom closing function to the window's close button
    root.protocol("WM_DELETE_WINDOW", on_closing)

    # Start the Tkinter event loop
    root.mainloop()
    print("Application has been closed.")


if __name__ == "__main__":
    main()