"""GUI layer for Manjaro Log Helper.

Loads the GtkBuilder UI definition (ui/main.ui) and wires up signal
handlers to the core logic in mlh_core.py. Uses libadwaita for system
theme integration.
"""

import os
import gettext
import gi
from concurrent.futures import ThreadPoolExecutor

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Gtk, GLib, Gio, Adw

from mlh_core import (
    collect_logs,
    send_to_internet,
    copy_to_clipboard,
    open_url,
    open_log_file,
    remove_personal_data,
    DEFAULT_EXPIRE_DAYS,
    __version__,
)

# Set up gettext for translations
base_dir = os.path.abspath(os.path.dirname(__file__))
# Check for local locale directory (for development) or system locale directory
local_locale_dir = os.path.join(base_dir, "locale")
system_locale_dir = os.path.join(base_dir, "usr", "share", "locale")

if os.path.exists(local_locale_dir):
    locale_dir = local_locale_dir
elif os.path.exists(system_locale_dir):
    locale_dir = system_locale_dir
else:
    locale_dir = "/usr/share/locale"

gettext.bindtextdomain("manjaro-log-helper", locale_dir)
gettext.textdomain("manjaro-log-helper")
_ = gettext.gettext

UI_FILE = os.path.join(os.path.dirname(__file__), "ui", "main.ui")
ICON_FILE = "/usr/share/icons/hicolor/scalable/apps/mlh.svg"


class ManjaroLogHelper:
    """Controller that loads the UI from the GtkBuilder XML file."""

    def __init__(self, application=None):
        self._builder = Gtk.Builder()
        self._builder.set_translation_domain("manjaro-log-helper")
        self._builder.add_from_file(UI_FILE)

        self.window = self._builder.get_object("main_window")
        if application is not None:
            self.window.set_application(application)

        header_bar = self._builder.get_object("header_bar")
        app_icon = Gtk.Image.new_from_file(ICON_FILE)
        app_icon.set_pixel_size(32)
        app_icon.set_margin_end(8)
        header_bar.pack_start(app_icon)

        try:
            from gi.repository import GdkPixbuf
            pixbuf = GdkPixbuf.Pixbuf.new_from_file(ICON_FILE)
            self.window.set_icon(pixbuf)
        except Exception:
            self.window.set_icon_name("mlh")

        self.window.connect("close-request", self.on_destroy)
        self._builder.get_object("button_cancel").connect(
            "clicked", self.on_quit_clicked
        )
        self._builder.get_object("button_generate").connect(
            "clicked", self.on_generate_clicked
        )

        if application is not None:
            self._setup_menu_actions(application)

        self._setup_menu_button()

        self.progress_bar = self._builder.get_object("progress_bar")
        self.status_label = self._builder.get_object("status_label")
        self.check_send = self._builder.get_object("check_send")

        self.log_checks = [
            "check_journal0",
            "check_journal1",
            "check_journal2",
            "check_install",
            "check_blame",
            "check_lspci",
            "check_lspcit",
            "check_lsusb",
            "check_inxi",
        ]

        self.window.present()

    # -- Signal handlers --------------------------------------------------

    def on_destroy(self, *args):
        return False

    def on_quit_clicked(self, button):
        self.window.destroy()

    def on_generate_clicked(self, button):
        selected = [
            cid
            for cid in self.log_checks
            if self._builder.get_object(cid).get_active()
        ]

        if not selected:
            self._set_status(_("No log selected. Please choose at least one."))
            return

        self._set_status(_("Collecting logs, please wait..."))
        self.progress_bar.set_visible(True)
        self.progress_bar.pulse()

        self._executor = ThreadPoolExecutor(max_workers=1)
        self._executor.submit(self._do_generate, selected)

    # -- Internal helpers -------------------------------------------------

    def _do_generate(self, selected):
        try:
            collect_logs(selected)
            
            # FIX: Rimozione dati sensibili SEMPRE, in ogni caso
            remove_personal_data()

            if self.check_send.get_active():
                url = send_to_internet(DEFAULT_EXPIRE_DAYS)
                copied = copy_to_clipboard(url)
                opened = open_url(url)
                notes = []
                if not copied:
                    notes.append(_("Could not copy URL to clipboard (xclip/wl-copy missing?)."))
                if not opened:
                    notes.append(_("Could not open browser automatically."))
                
                status = (
                    f"✅ {_('Logs sent successfully!')}\n"
                    f"{_('URL:')} {url}\n"
                    f"🔒 {_('Personal data has been automatically removed before sharing.')}\n"
                    f"({_('This link will be deleted after')} {DEFAULT_EXPIRE_DAYS} {_('days')})"
                )
                if notes:
                    status += "\n" + " ".join(notes)
                self._set_status(status)
            else:
                # Log salvato localmente: i dati sono già stati rimossi sopra
                self._set_status(
                    f"✅ {_('Log file created.')}\n"
                    f"🔒 {_('Personal data has been automatically removed.')}"
                )
                if not open_log_file():
                    self._set_status(
                        _("Log file created, but could not open it automatically.")
                    )
        except Exception as exc:
            self._set_status(f"❌ {_('Error')}: {exc}")
        finally:
            GLib.idle_add(self.progress_bar.set_visible, False)

    def _set_status(self, text):
        self.status_label.set_text(text)

    def _set_status_markup(self, markup):
        self.status_label.set_markup(markup)

    def _setup_menu_button(self):
        """Set up the hamburger menu button with a popover menu."""
        menu_button = self._builder.get_object("menu_button")
        
        menu_model = Gio.Menu.new()
        
        about_section = Gio.Menu.new()
        about_section.append(_("About"), "app.about")
        menu_model.append_section(None, about_section)
        
        disclaimer_section = Gio.Menu.new()
        disclaimer_section.append(_("Disclaimer"), "app.disclaimer")
        menu_model.append_section(None, disclaimer_section)
        
        bug_section = Gio.Menu.new()
        bug_section.append(_("Report a Bug"), "app.report-bug")
        menu_model.append_section(None, bug_section)
        
        popover = Gtk.PopoverMenu.new_from_model(menu_model)
        menu_button.set_popover(popover)

    def _setup_menu_actions(self, application):
        """Set up menu actions for the hamburger menu."""
        about_action = Gio.SimpleAction.new("about", None)
        about_action.connect("activate", self.on_about)
        application.add_action(about_action)

        disclaimer_action = Gio.SimpleAction.new("disclaimer", None)
        disclaimer_action.connect("activate", self.on_disclaimer)
        application.add_action(disclaimer_action)

        bug_action = Gio.SimpleAction.new("report-bug", None)
        bug_action.connect("activate", self.on_report_bug)
        application.add_action(bug_action)

    def on_about(self, action, param):
        """Show about dialog."""
        about_dialog = Adw.AboutDialog.new()
        about_dialog.set_application_name("Manjaro Log Helper")
        about_dialog.set_version(__version__)
        about_dialog.set_developer_name("Stefano Capitani")
        about_dialog.set_copyright("© 2024 Stefano Capitani")
        about_dialog.set_website("https://codeberg.org/Ste74/manjaro-log-helper")
        about_dialog.set_license_type(Gtk.License.GPL_3_0)
        about_dialog.set_comments(_("A tool to collect and share Manjaro system logs for troubleshooting.\n\nOriginal idea by the BigLinux team."))
        about_dialog.present(self.window)

    def on_disclaimer(self, action, param):
        """Show disclaimer dialog."""
        dialog = Adw.MessageDialog.new(
            self.window,
            _("Disclaimer"),
            _(
                "This tool collects system logs and automatically removes personal data "
                "such as hostnames, usernames, IP addresses, MAC addresses, email addresses, "
                "UUIDs, and file paths before saving or sharing them. "
                "However, automatic sanitization may not catch all sensitive information. "
                "Please review the generated logs before sharing them publicly. "
                "The author is not responsible for any data accidentally disclosed."
            )
        )
        dialog.add_response("ok", _("OK"))
        dialog.set_default_response("ok")
        dialog.set_close_response("ok")
        dialog.present()

    def on_report_bug(self, action, param):
        """Open bug report page."""
        open_url("https://codeberg.org/Ste74/manjaro-log-helper/issues")


def main():
    app = Adw.Application(application_id="org.manjaro.LogHelper")
    app.connect("activate", lambda a: ManjaroLogHelper(application=a))
    app.run(None)


if __name__ == "__main__":
    main()