#!/usr/bin/env python3
import sys
import argparse
import gi

gi.require_version('Gtk', '3.0')
try:
    gi.require_version('WebKit2', '4.1')
except ValueError:
    gi.require_version('WebKit2', '4.0')

from gi.repository import Gtk, WebKit2, GLib

class GrimOSBrowser(Gtk.Window):
    def __init__(self, url):
        super().__init__(type=Gtk.WindowType.TOPLEVEL)
        
        # Remove borders to blend with Tkinter
        self.set_decorated(False)
        self.set_skip_taskbar_hint(True)
        
        # Ensure window accepts focus
        self.set_accept_focus(True)
        self.set_can_focus(True)
        
        # WebView
        self.webview = WebKit2.WebView()
        self.webview.set_can_focus(True)
        self.webview.load_uri(url)
        
        # Monitor URL changes
        self.webview.connect("notify::uri", self.on_uri_changed)
        
        # Download manager
        context = WebKit2.WebContext.get_default()
        context.connect("download-started", self.on_download_started)
        
        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.add(self.webview)
        self.add(scrolled_window)
        
        self.connect("destroy", Gtk.main_quit)
        
        # Manual focus handling
        self.webview.add_events(gi.repository.Gdk.EventMask.BUTTON_PRESS_MASK)
        self.webview.connect("button-press-event", self.on_click)
        
        # Listen to stdin for commands from GrimOS
        GLib.io_add_watch(0, GLib.IO_IN, self.on_stdin)

    def on_uri_changed(self, webview, param):
        uri = webview.get_uri()
        if uri:
            print(f"URL {uri}", flush=True)

    def on_download_started(self, context, download):
        download.connect("decide-destination", self.on_download_decide_destination)
        download.connect("finished", self.on_download_finished)

    def on_download_decide_destination(self, download, suggested_filename):
        import os
        dl_dir = os.path.expanduser("~/Téléchargements")
        os.makedirs(dl_dir, exist_ok=True)
        dest_path = os.path.join(dl_dir, suggested_filename)
        download.set_destination("file://" + dest_path)
        print(f"DOWNLOAD_START {dest_path}", flush=True)
        return True

    def on_download_finished(self, download):
        print(f"DOWNLOAD_FINISH", flush=True)

    def on_click(self, widget, event):
        self.present()
        self.webview.grab_focus()
        return False

    def on_stdin(self, source, condition):
        try:
            line = sys.stdin.readline()
            if not line: # EOF
                Gtk.main_quit()
                return False
                
            parts = line.strip().split()
            if not parts: return True
            
            cmd = parts[0]
            if cmd == "MOVE" and len(parts) >= 5:
                x, y, w, h = map(int, parts[1:5])
                if w > 0 and h > 0:
                    self.resize(w, h)
                    self.move(x, y)
            elif cmd == "LOAD" and len(parts) >= 2:
                self.webview.load_uri(parts[1])
            elif cmd == "BACK":
                self.webview.go_back()
        except Exception as e:
            pass
        return True # Continue listening

def main():
    parser = argparse.ArgumentParser(description="Moteur WebKitGTK Overlay pour GrimOS")
    parser.add_argument("--url", type=str, default="https://duckduckgo.com", help="URL")
    
    args = parser.parse_args()
    
    url = args.url
    if not url.startswith("http://") and not url.startswith("https://") and not url.startswith("file://"):
        url = "https://" + url

    app = GrimOSBrowser(url)
    app.show_all()
    
    Gtk.main()

if __name__ == '__main__':
    main()
