import sys
import os
import tkinter as tk

# Add project root to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from core.config import load_settings
from core.desktop import Desktop

def main():
    settings = load_settings()
    
    root = tk.Tk()
    root.config(cursor="left_ptr")
    root.title("GrimOS")
    
    def on_global_click(event):
        try:
            if hasattr(event.widget, 'focus_target'):
                event.widget.focus_target.focus_set()
            else:
                event.widget.focus_set()
        except Exception:
            pass
            
        w = event.widget
        while hasattr(w, 'master') and w.master:
            if w.__class__.__name__ == 'Window':
                w.lift()
                break
            w = w.master
            
    root.bind_all("<ButtonPress-1>", on_global_click, add="+")
    
    if settings.get("fullscreen", False):
        w = root.winfo_screenwidth()
        h = root.winfo_screenheight()
        root.geometry(f"{w}x{h}+0+0")
        root.attributes('-fullscreen', True)
    else:
        res = settings.get("resolution", "1024x768")
        root.geometry(res)
        
    theme_name = settings.get("theme", "GrimOS")
    from core.theme import apply_theme
    apply_theme(root, theme_name)
        
    desktop = Desktop(root, settings)
    desktop.restart_requested = False
    
    root.mainloop()
    
    if getattr(desktop, "restart_requested", False):
        script = os.path.abspath(sys.argv[0])
        os.execl(sys.executable, sys.executable, script)

if __name__ == "__main__":
    main()
