#!/usr/bin/python3

# waydroid-helper.in
#
# Copyright 2024 rikka
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import os
import sys
import signal
import locale
import gettext
import shutil
from argparse import ArgumentParser

VERSION = '0.3.0'
BUILD_APPIMAGE = 'False'
if BUILD_APPIMAGE == 'True':
    appdir = os.environ.get('APPDIR')
    pkgdatadir = os.path.join(appdir, '/usr/share/waydroid-helper'.lstrip('/'))
    os.environ['XDG_DATA_DIRS']=f"{os.environ.get('XDG_DATA_DIRS','')}:{os.path.join(appdir, '/usr/share'.lstrip('/'))}"
    os.environ['PATH']=f"{os.path.join(appdir, '/usr/bin'.lstrip('/'))}:{os.environ.get('PATH','')}"
    cli_path = os.path.join(appdir, '/usr/bin'.strip('/'),'waydroid-cli')
    dest_path = os.path.join('/tmp', 'waydroid-helper', 'waydroid-cli')
    os.makedirs(os.path.dirname(dest_path), exist_ok=True)
    shutil.copy(cli_path, dest_path) 
    os.environ['WAYDROID_CLI_PATH']=dest_path
    localedir = os.path.join(appdir, '/usr/share/locale'.lstrip('/'))
else:
    pkgdatadir = '/usr/share/waydroid-helper'
    localedir = '/usr/share/locale'
    os.environ['WAYDROID_CLI_PATH']=os.path.join('/usr/bin','waydroid-cli')
project_name = 'waydroid-helper'

sys.path.insert(1, pkgdatadir)
os.environ['PKGDATADIR'] = pkgdatadir
os.environ['PROJECT_NAME'] = project_name
signal.signal(signal.SIGINT, signal.SIG_DFL)
locale.bindtextdomain('waydroid-helper', localedir)
locale.textdomain('waydroid-helper')
# gettext.install('waydroid-helper', localedir)

gettext.bindtextdomain('waydroid-helper', localedir)
gettext.textdomain('waydroid-helper')

from waydroid_helper.build_features import EMBEDDED_WINDOW, GAMEPAD

def start_gui(emulator=False):
    # Gio resolves schemas when the first Settings object is constructed.
    # Prefer this installation's compiled schemas in a relocatable prefix.
    datadir = os.path.dirname(pkgdatadir)
    if os.path.isfile(os.path.join(datadir, 'glib-2.0', 'schemas', 'gschemas.compiled')):
        dirs = os.environ.get('XDG_DATA_DIRS') or '/usr/local/share:/usr/share'
        if datadir not in dirs.split(os.pathsep):
            os.environ['XDG_DATA_DIRS'] = datadir + os.pathsep + dirs
    import gi

    libdir = '/usr/lib/aarch64-linux-gnu'
    if BUILD_APPIMAGE == 'True':
        libdir = os.path.join(appdir, libdir.lstrip('/'))
    if emulator:
        # GI must find the typelibs and libraries from this installation.
        repo = gi.Repository.get_default()
        repo.prepend_search_path(os.path.join(libdir, 'girepository-1.0'))
        repo.prepend_library_path(libdir)
        casilda_libdir = os.path.join(libdir, 'waydroid-helper', 'casilda')
        repo.prepend_search_path(casilda_libdir)
        repo.prepend_library_path(casilda_libdir)
        if GAMEPAD:
            gamepad_libdir = os.path.join(libdir, 'waydroid-helper', 'gamepad')
            repo.prepend_search_path(gamepad_libdir)
            repo.prepend_library_path(gamepad_libdir)

        # GTK selects its renderer when the native window is realized. Read
        # the emulator-only preference before importing GTK, leaving an
        # explicit command-line environment override available for debugging.
        from gi.repository import Gio
        renderer = Gio.Settings.new('com.jaoushingan.WaydroidHelper').get_string('emulator-window-renderer')
        if renderer != 'auto':
            os.environ.setdefault('GSK_RENDERER', renderer)

    gi.require_version('Adw', '1')
    gi.require_version("Gtk", "4.0")
    gi.require_version("GLib", "2.0")
    from gi.repository import Gio, Adw, Gtk, GLib
    resource = Gio.Resource.load(os.path.join(pkgdatadir, 'waydroid-helper.gresource'))
    resource._register()
    if emulator:
        # The management application can remain open. Use an ordinary append
        # logger for this independent GUI process so opening/raising it does
        # not truncate the shared helper log or create another log listener.
        os.environ["WAYDROID_HELPER_EMULATOR"] = "1"
        from gi.repository import Gdk
        from waydroid_helper.controller.app.window import create_keymapper
        from waydroid_helper.controller.app.embedded_session import compositor_type
        compositor_type()
        sys.exit(create_keymapper(Gdk.Display.get_default().get_name(), embedded=True))
    from waydroid_helper import main
    sys.exit(main.main(VERSION))

if __name__ == '__main__':
    # 确保 PyInstaller/AppImage 下的 multiprocessing 使用 spawn 时能够正确处理
    # 子进程的引导参数，避免 argparse 误解析 Python 内部参数。
    import multiprocessing
    multiprocessing.freeze_support()

    parser = ArgumentParser()
    parser.add_argument("--open-extension", metavar="ID", help="Open an extension detail page")
    parser.set_defaults(emulator=False)
    if EMBEDDED_WINDOW:
        parser.add_argument("--emulator", action="store_true", help="Open the experimental embedded Waydroid window")
    parser.add_argument("--start-mount", action="store_true", help="Start the mounting service")
    parser.add_argument("--start-monitor", action="store_true", help="Start the monitoring service")
    parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
    parser.add_argument(
        "--log-level",
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
        default='INFO',
        help="Set the logging level (default: INFO)"
    )
    args = parser.parse_args()

    os.environ['LOG_LEVEL'] = args.log_level.upper()

    if args.start_mount:
        from waydroid_helper.tools import start_monitor, start_mount
        start_mount()
    elif args.start_monitor:
        from waydroid_helper.tools import start_monitor, start_mount
        start_monitor()
    else:
        start_gui(emulator=args.emulator)

