import os
import sys
import time
import tkinter as tk

# Ajouter le chemin racine
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

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

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--app', type=str, help="Lancer et capturer une application spécifique (module name ou 'bureau')")
    parser.add_argument('--output', type=str, required=True, help="Fichier de sortie")
    parser.add_argument('--filepath', type=str, default=None, help="Fichier à ouvrir dans l'app")
    args = parser.parse_args()

    settings = load_settings()
    root = tk.Tk()
    root.geometry("1024x600+0+0")
    root.overrideredirect(True)
    root.attributes('-topmost', True)
    root.update_idletasks()
    
    desktop = Desktop(root, settings)
    
    def capture_and_exit(window=None):
        out = args.output
        os.makedirs(os.path.dirname(out), exist_ok=True)
        
        # Attendre que Tkinter dessine bien la fenêtre
        root.update()
        
        from PIL import ImageGrab
        if window:
            # Capturer une fenêtre spécifique via ses coordonnées
            x = window.winfo_rootx()
            y = window.winfo_rooty()
            w = window.winfo_width()
            h = window.winfo_height()
            
            # Recadrer via bbox (left, top, right, bottom)
            img = ImageGrab.grab(bbox=(x, y, x+w, y+h))
        else:
            # Capturer tout l'écran (la fenêtre root)
            rx = root.winfo_rootx()
            ry = root.winfo_rooty()
            rw = root.winfo_width()
            rh = root.winfo_height()
            img = ImageGrab.grab(bbox=(rx, ry, rx+rw, ry+rh))
            
        img.save(out)
        print(f"Capture enregistrée : {out}")
        root.destroy()
        sys.exit(0)
        
    def step1():
        if args.app == 'bureau':
            root.after(1000, lambda: capture_and_exit())
            return
            
        # Chercher l'app
        app_to_launch = None
        for a in desktop.apps:
            if args.app.lower() in a.get("module").lower() or args.app.lower() in a.get("name").lower():
                app_to_launch = a
                break
                
        if app_to_launch:
            kwargs = {}
            if args.filepath:
                kwargs['filepath'] = os.path.abspath(args.filepath)
            desktop.app_manager.launch_app(app_to_launch, **kwargs)
            # Attendre l'ouverture et chercher la fenêtre
            def wait_for_win():
                if desktop.app_manager.active_windows:
                    win = desktop.app_manager.active_windows[-1]
                    root.after(1000, lambda: capture_and_exit(win))
                else:
                    root.after(100, wait_for_win)
            root.after(500, wait_for_win)
        else:
            print(f"Application introuvable : {args.app}")
            capture_and_exit()
            
    root.after(2000, step1)
    root.mainloop()

if __name__ == "__main__":
    main()
