# controlpanel/__main__.py
"""
Entry point for the Control Panel application when run as a module
using `python -m controlpanel`.
"""

# --- Standard library imports ---
import tkinter as tk
import sys
import logging
import os

# --- Configuration and Core App Import ---
from controlpanel import config
from controlpanel.logging_config import setup_logging
from controlpanel.app_main import ControlPanelApp, MAP_MODULES_LOADED

# --- Setup Logging ---
try:
    setup_logging()
except Exception as log_setup_err:
    print(f"ERROR setting up logging: {log_setup_err}")
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
    )

# --- Main Execution Block ---
def main():
    """Main function to create and run the application."""
    root = None
    app_instance = None
    try:
        # Check for critical map library dependencies if map is enabled
        if config.ENABLE_MAP_OVERLAY and not MAP_MODULES_LOADED:
            msg = "Map is enabled in config, but required map modules failed to load."
            logging.critical(f"[App Main] {msg}")
            print(f"CRITICAL ERROR: {msg} Check logs for missing libraries (e.g., mercantile, pyproj).")
            sys.exit(1)

        # Import UI components just before use
        try:
            from controlpanel.gui.ui import create_main_window
        except ImportError as ui_import_err:
             logging.critical(f"Failed to import UI components: {ui_import_err}", exc_info=True)
             print(f"CRITICAL ERROR: Failed to import UI components: {ui_import_err}")
             sys.exit(1)

        # Create the main Tkinter window
        root = create_main_window(
            "Control Panel",
            config.TKINTER_MIN_WIDTH,
            config.TKINTER_MIN_HEIGHT,
            10,
            10,  # Initial position; app constructor calculates the final one
        )
        
        # Instantiate the main application class, which now handles all setup
        app_instance = ControlPanelApp(root)

        # Set the window close protocol handler
        root.protocol("WM_DELETE_WINDOW", app_instance.close_app)

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

    except SystemExit as exit_e:
        exit_code = exit_e.code if isinstance(exit_e.code, int) else 1
        log_level = logging.INFO if exit_code == 0 else logging.WARNING
        logging.log(log_level, f"[App Main] Application exited via sys.exit({exit_code}).")
    
    except ImportError as imp_err:
        logging.critical(
            f"[App Main] CRITICAL IMPORT ERROR: {imp_err}. Application cannot start.",
            exc_info=True,
        )
        print(f"\nCRITICAL ERROR: Missing a required library - {imp_err}\n")
        sys.exit(1)
        
    except Exception as e:
        logging.critical(
            "[App Main] UNHANDLED EXCEPTION during startup or main loop:", exc_info=True
        )
        print("\nFATAL ERROR: An unhandled exception occurred. Check logs for details.\n")
        if app_instance and hasattr(app_instance, 'close_app'):
            try:
                logging.info("Attempting graceful shutdown after unhandled exception...")
                app_instance.close_app()
            except Exception as shutdown_err:
                logging.error(f"Error during forced shutdown: {shutdown_err}")
        sys.exit(1)
        
    finally:
        logging.info("=== App End ===")
        logging.shutdown()


if __name__ == "__main__":
    main()