# -*- coding: utf-8 -*-
import tkinter as tk
import sys
import os

# Ensure local imports work correctly
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from pymsc.gui.main_window import MainWindow
from pymsc.gui.pages.control_page import ControlPage
from pymsc.gui.pages.mission_page import MissionPage
from pymsc.utils.logger import CustomLogger
from pymsc.utils.profiler import print_stats, save_stats_to_csv

def main():
    """
    Application Entry Point.
    Sets up the environment, GUI pages, and starts the main loop.
    """
    # Initialize Logger
    custom_logger = CustomLogger(log_file="pymsc.log", use_console=True)
    logger = custom_logger.get_logger()
    logger.info("Starting PyMsc System...")

    # Main Window Setup
    root = tk.Tk()
    app = MainWindow(root)

    # Register Pages as real Tabs
    app.add_page("Control", ControlPage)
    app.add_page("Mission", MissionPage)

    def shutdown():
        """Graceful cleanup."""
        logger.info("Shutting down. Exporting metrics...")
        save_stats_to_csv("performance_report.csv")
        print_stats()
        app.on_close()

    root.protocol("WM_DELETE_WINDOW", shutdown)

    # Auto-start hardware communication
    app.start_mission()

    root.mainloop()

if __name__ == "__main__":
    main()