#!/usr/bin/python3

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

import sys
import os
import subprocess
import re

def get_flatpak_app_id_from_desktop(desktop_file):
    """Extract Flatpak app ID from desktop file"""
    try:
        with open(desktop_file, 'r') as f:
            content = f.read()
            
        # Look for the Flatpak app ID in various ways
        # Method 1: X-Flatpak key
        match = re.search(r'^X-Flatpak=(.+)$', content, re.MULTILINE)
        if match:
            return match.group(1).strip()
            
        # Method 2: From file path if it's in flatpak exports
        if 'flatpak' in desktop_file and 'exports' in desktop_file:
            # Path like: ~/.local/share/flatpak/exports/share/applications/com.example.App.desktop
            basename = os.path.basename(desktop_file)
            if basename.endswith('.desktop'):
                app_id = basename[:-8]  # Remove .desktop
                return app_id
                
        # Method 3: Try to parse from Exec line
        exec_match = re.search(r'^Exec=.*flatpak run ([^\s]+)', content, re.MULTILINE)
        if exec_match:
            return exec_match.group(1).strip()
            
        return None
        
    except Exception as e:
        print(f"Error reading desktop file: {e}")
        return None

def remove_flatpak_app(app_id):
    """Remove flatpak app using pkexec"""
    try:
        # Create confirmation dialog
        dialog = Gtk.MessageDialog(
            parent=None,
            flags=Gtk.DialogFlags.MODAL,
            type=Gtk.MessageType.QUESTION,
            buttons=Gtk.ButtonsType.YES_NO,
            text=f"Remove Flatpak application '{app_id}'?\n\nThis will uninstall the application from your system."
        )
        
        response = dialog.run()
        dialog.destroy()
        
        if response != Gtk.ResponseType.YES:
            return False
            
        # Show progress dialog
        progress = Gtk.MessageDialog(
            parent=None,
            flags=Gtk.DialogFlags.MODAL,
            type=Gtk.MessageType.INFO,
            buttons=Gtk.ButtonsType.NONE,
            text=f"Removing {app_id}..."
        )
        progress.show_all()
        
        while Gtk.events_pending():
            Gtk.main_iteration()
        
        # Use pkexec to remove the flatpak (system-wide) or direct command (user)
        # Try user-level first
        result = subprocess.run(['flatpak', 'uninstall', '--user', '--assumeyes', app_id], 
                              capture_output=True, text=True)
        
        if result.returncode != 0:
            # Try system-level with pkexec
            result = subprocess.run(['pkexec', 'flatpak', 'uninstall', '--system', '--assumeyes', app_id], 
                                  capture_output=True, text=True)
        
        progress.destroy()
        
        if result.returncode == 0:
            success_dialog = Gtk.MessageDialog(
                parent=None,
                flags=0,
                type=Gtk.MessageType.INFO,
                buttons=Gtk.ButtonsType.OK,
                text="Flatpak erfolgreich entfernt!"
            )
            success_dialog.format_secondary_text(f"Die Anwendung '{app_id}' wurde erfolgreich von Ihrem System entfernt.")
            success_dialog.run()
            success_dialog.destroy()
            return True
        else:
            error_dialog = Gtk.MessageDialog(
                parent=None,
                flags=0,
                type=Gtk.MessageType.ERROR,
                buttons=Gtk.ButtonsType.OK,
                text=f"Fehler beim Entfernen von {app_id}"
            )
            error_dialog.format_secondary_text(f"Details: {result.stderr}")
            error_dialog.run()
            error_dialog.destroy()
            return False
            
    except Exception as e:
        error_dialog = Gtk.MessageDialog(
            parent=None,
            flags=0,
            type=Gtk.MessageType.ERROR,
            buttons=Gtk.ButtonsType.OK,
            text=f"Error: {str(e)}"
        )
        error_dialog.run()
        error_dialog.destroy()
        return False

def remove_flatpak_app_cli(app_id):
    """Remove flatpak app using command line (fallback for no GUI)"""
    try:
        print(f"Removing Flatpak app: {app_id}")
        
        # Try user-level first
        result = subprocess.run(['flatpak', 'uninstall', '--user', '--assumeyes', app_id], 
                              capture_output=True, text=True)
        
        if result.returncode != 0:
            # Try system-level with pkexec
            result = subprocess.run(['pkexec', 'flatpak', 'uninstall', '--system', '--assumeyes', app_id], 
                                  capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"Flatpak '{app_id}' erfolgreich entfernt!")
            return True
        else:
            print(f"Fehler beim Entfernen von '{app_id}': {result.stderr}")
            return False
            
    except Exception as e:
        print(f"Error: {str(e)}")
        return False

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: guideos-remove-flatpak /path/to/app.desktop [--dry-run]")
        sys.exit(1)
        
    desktop_file = sys.argv[1]
    dry_run = len(sys.argv) > 2 and sys.argv[2] == '--dry-run'
    
    if not os.path.exists(desktop_file):
        print(f"Desktop file not found: {desktop_file}")
        sys.exit(1)
    
    app_id = get_flatpak_app_id_from_desktop(desktop_file)
    
    if not app_id:
        print("Could not determine Flatpak app ID from desktop file")
        sys.exit(1)
    
    print(f"Found Flatpak app ID: {app_id}")
    
    if dry_run:
        print(f"DRY RUN: Would remove Flatpak app {app_id}")
        sys.exit(0)
    
    # Try GUI version first, fall back to CLI if no display
    try:
        if os.environ.get('DISPLAY'):
            success = remove_flatpak_app(app_id)
        else:
            success = remove_flatpak_app_cli(app_id)
    except Exception as e:
        print(f"GUI failed, trying CLI: {e}")
        success = remove_flatpak_app_cli(app_id)
    
    if success:
        sys.exit(0)
    else:
        sys.exit(1)