#!/usr/bin/env python3
import gi
import subprocess
import os
import time

gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
from gi.repository import Gtk, Gst, Gdk, GLib

class CinnamonRecorder(Gtk.Window):
    def __init__(self):
        super().__init__(title="Pro Recorder")
        self.set_default_size(300, 150)
        self.set_border_width(10)
        
        self.recording_process = None
        
        # 1. Main UI Layout
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.add(vbox)

        self.btn_toggle = Gtk.Button(label="🔴 START RECORDING")
        self.btn_toggle.connect("clicked", self.on_toggle)
        vbox.pack_start(self.btn_toggle, True, True, 0)

        self.status = Gtk.Label(label="Status: Ready")
        vbox.pack_start(self.status, False, False, 0)

        # 2. Permanent PiP Window
        self.pip = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
        self.pip.set_keep_above(True)
        self.pip.set_decorated(False)
        self.pip.set_default_size(320, 180)
        self.pip.set_skip_taskbar_hint(True)
        
        # Position top-right
        screen = Gdk.Screen.get_default()
        self.pip.move(screen.get_width() - 340, 40)

        # 3. GStreamer Preview Setup
        Gst.init(None)
        # Using gtksink directly as it's the most reliable GTK3 method in 2026
        self.pipeline = Gst.parse_launch(
            "ximagesrc ! videoconvert ! videoscale ! video/x-raw,width=640,height=360 ! gtksink name=sink"
        )
        sink = self.pipeline.get_by_name("sink")
        preview_widget = sink.get_property("widget")
        self.pip.add(preview_widget)

        self.connect("destroy", self.quit_app)
        self.show_all()
        self.pip.show_all()
        self.pipeline.set_state(Gst.State.PLAYING)

    def on_toggle(self, widget):
        if self.recording_process is None:
            output = os.path.expanduser(f"~/Videos/Rec_{int(time.time())}.mp4")
            # Optimized x11grab for Cinnamon
            cmd = [
                "ffmpeg", "-f", "x11grab", "-video_size", "1920x1080", 
                "-framerate", "30", "-i", os.environ.get("DISPLAY", ":0.0"),
                "-c:v", "libx264", "-preset", "ultrafast", "-y", output
            ]
            self.recording_process = subprocess.Popen(cmd, stdin=subprocess.PIPE)
            self.btn_toggle.set_label("⏹ STOP RECORDING")
            self.status.set_text("RECORDING...")
        else:
            self.recording_process.communicate(input=b'q')
            self.recording_process = None
            self.btn_toggle.set_label("🔴 START RECORDING")
            self.status.set_text("Saved to Videos")

    def quit_app(self, widget):
        if self.recording_process: self.recording_process.terminate()
        self.pipeline.set_state(Gst.State.NULL)
        Gtk.main_quit()

if __name__ == "__main__":
    win = CinnamonRecorder()
    Gtk.main()
