# settings.py
#
# Copyright 2024 Hari Rana (TheEvilSkeleton)
#
# 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
from pathlib import Path

from gi.repository import GLib, Gio, Xdp


def get_user_config_dir() -> str:
    """Retrieve the user's config directory."""
    if not Xdp.Portal.running_under_sandbox():
        return GLib.get_user_config_dir()

    return os.environ.get(
        "HOST_XDG_CONFIG_HOME", str(Path(GLib.get_home_dir(), "." + "config"))
    )


def get_user_data_dir() -> str:
    """Retrieve the user's data directory."""
    if not Xdp.Portal.running_under_sandbox():
        return GLib.get_user_data_dir()

    return os.environ.get(
        "HOST_XDG_DATA_HOME",
        str(Path(GLib.get_home_dir(), "." + "local", "share")),
    )


def get_system_data_dirs() -> list[str]:
    """Retrieve the system's data directory."""
    data_dirs = GLib.get_system_data_dirs()

    if Xdp.Portal.running_under_flatpak():
        data_dirs.remove(str(Path(os.sep, "app", "share")))

    return data_dirs


def get_debug_info() -> str:
    """Retrieve important information for debugging."""
    environment_variables = (
        "XDG_DATA_DIRS",
        "XDG_CONFIG_HOME",
        "XDG_DATA_HOME",
        "HOST_XDG_CONFIG_HOME",
        "HOST_XDG_DATA_HOME",
    )

    home = Path(GLib.get_home_dir()).name
    output = ""
    for environment_variable in environment_variables:
        original = f"{environment_variable}: “{GLib.getenv(environment_variable)}”\n"
        output += original.replace(home, "[REDACTED]")

    return str(output)


def create_schema_sources_list() -> list[Gio.SettingsSchemaSource]:
    """Create a list schema sources based on the user's system data directory."""
    sources = []

    for data_dir in GLib.get_system_data_dirs():
        path = Path(data_dir, "glib-2.0", "schemas")
        if path.is_dir():
            source = Gio.SettingsSchemaSource.new_from_directory(str(path), None, True)
            sources.append(source)

    return sources
