from UCwinRoadCOM import *
from LoggerProxy import LoggerProxy
import time
import signal

# Our modularized components
from flow_sync import handlers
from flow_sync.ribbon_ui import RibbonUI

# Globals expected by UC-win/Road script model
ribbon: RibbonUI | None = None
winRoadProxy: UCwinRoadComProxy | None = None
const = None
logProxy: LoggerProxy | None = None


def check_simulation_status():
    global winRoadProxy, ribbon, logProxy
    try:
        if not winRoadProxy or not ribbon:
            return
        if not winRoadProxy.ApplicationServices.IsPythonScriptRun:
            logProxy.logger.info("UC-win/Road requested script termination. Shutting down.")
            ribbon.tk_root.quit()
        else:
            ribbon.tk_root.after(500, check_simulation_status)  # Reduced frequency to avoid GIL issues
    except Exception as e:
        if logProxy:
            logProxy.logger.error(f"Error in status check loop: {e}")
        if ribbon and ribbon.tk_root:
            ribbon.tk_root.quit()


def shutdown_handler(sig, frame):
    global ribbon, logProxy
    if logProxy:
        logProxy.logger.warning("Ctrl+C detected! Initiating graceful shutdown...")
    if ribbon and ribbon.tk_root:
        ribbon.tk_root.quit()


def main():
    signal.signal(signal.SIGINT, shutdown_handler)
    start_time = time.perf_counter_ns()
    global winRoadProxy, const, logProxy, ribbon

    try:
        winRoadProxy = UCwinRoadComProxy()
        const = winRoadProxy.const
        scriptName = 'FlowSync'
        logfilepath = winRoadProxy.PythonPluginDirectory() + scriptName + '.log'
        logProxy = LoggerProxy(scriptName, logfilepath)
        logProxy.logger.info(f'Starting {scriptName}')

        ribbon = RibbonUI(winRoadProxy, logProxy)
        handlers.set_context(ribbon, winRoadProxy, logProxy)
        ribbon.MakeRibbonUI()
        logProxy.logger.info('Ribbon UI created')

        winRoadProxy.ApplicationServices.IsPythonScriptRun = True
        logProxy.logger.info("Signaled to UC-win/Road: Script is now active.")

        logProxy.logger.info("Starting Tkinter main loop and simulation status checker.")
        ribbon.tk_root.after(100, check_simulation_status)

        ribbon.tk_root.mainloop()

    except Exception as e:
        if logProxy:
            logProxy.logger.error(f"Fatal error in main function: {e}")

    finally:
        try:
            if logProxy:
                logProxy.logger.info("Cleaning up resources...")
            if ribbon:
                ribbon.KillRibbonUI()
            if winRoadProxy:
                winRoadProxy.ApplicationServices.IsPythonScriptRun = False
            if logProxy:
                elapsed_time = time.perf_counter_ns() - start_time
                logProxy.logger.info(f"Total runtime: {elapsed_time/1000000:.2f}ms")
                logProxy.logger.info(f'End {scriptName}')
                logProxy.killLogger()
            if winRoadProxy:
                del winRoadProxy
        except Exception as e:
            if logProxy and logProxy.logger:
                logProxy.logger.error(f"Error during cleanup: {e}")


if __name__ == '__main__':
    main()