"""Service for generating and managing polkit rules for supervised accounts."""

import os

from big_parental_controls.core.constants import POLKIT_RULES_DIR, POLKIT_RULES_FILE

POLKIT_RULES_TEMPLATE = """\
// Generated by big-parental-controls
// DO NOT EDIT MANUALLY — changes will be overwritten
polkit.addRule(function(action, subject) {
    // Supervised accounts (supervised group) need admin auth for restricted actions
    if (subject.isInGroup("supervised")) {
        // Block package management
        var pkg_actions = [
            "org.manjaro.pamac.commit",
            "org.freedesktop.packagekit.package-install",
            "org.freedesktop.packagekit.package-remove",
            "org.freedesktop.Flatpak.app-install",
            "org.freedesktop.Flatpak.runtime-install",
            "org.freedesktop.Flatpak.app-uninstall"
        ];
        for (var i = 0; i < pkg_actions.length; i++) {
            if (action.id == pkg_actions[i]) {
                return polkit.Result.AUTH_ADMIN;
            }
        }
        // Block user/account management — deny entirely (not even admin auth)
        if (action.id.indexOf("org.freedesktop.accounts") === 0) {
            return polkit.Result.NO;
        }
        // Block disk/USB mounting
        if (action.id.indexOf("org.freedesktop.udisks2") === 0) {
            return polkit.Result.AUTH_ADMIN;
        }
        // Block network configuration changes
        if (action.id.indexOf("org.freedesktop.NetworkManager") === 0 &&
            action.id !== "org.freedesktop.NetworkManager.wifi.scan" &&
            action.id !== "org.freedesktop.NetworkManager.network-control") {
            return polkit.Result.AUTH_ADMIN;
        }
    }
});
"""


def install_polkit_rules() -> bool:
    """Install the polkit rules file for supervised accounts."""
    try:
        os.makedirs(POLKIT_RULES_DIR, exist_ok=True)
        with open(POLKIT_RULES_FILE, "w") as f:
            f.write(POLKIT_RULES_TEMPLATE)
        os.chmod(POLKIT_RULES_FILE, 0o644)
    except OSError:
        return False
    else:
        return True


def remove_polkit_rules() -> bool:
    """Remove the polkit rules file."""
    try:
        if os.path.exists(POLKIT_RULES_FILE):
            os.remove(POLKIT_RULES_FILE)
    except OSError:
        return False
    else:
        return True


def rules_installed() -> bool:
    """Check if the polkit rules file exists."""
    return os.path.isfile(POLKIT_RULES_FILE)
