#!/usr/bin/env python3
"""Query current edubuntu-installer state and output JSON."""

import grp
import json
import os
import pwd
import subprocess
import sys
from pathlib import Path

METAPACKAGES = (
    "ubuntu-edu-preschool",
    "ubuntu-edu-primary",
    "ubuntu-edu-secondary",
    "ubuntu-edu-tertiary",
    "ubuntu-edu-music",
    "ubuntu-edu-teaching",
    "edubuntu-fonts",
)

SCHEMA_DIR = Path("/usr/share/glib-2.0/schemas")

GSCHEMA_OVERRIDES = {
    "Preschool": SCHEMA_DIR / "96-edubuntu-preschool.gschema.override",
    "Primary/Elementary": SCHEMA_DIR / "96-edubuntu-primary.gschema.override",
    "Secondary/Middle/High School": SCHEMA_DIR / "96-edubuntu-secondary.gschema.override",
}

TERTIARY_LABEL = "Tertiary/College/University (Default)"

SETUP_CHOICES = [
    "Preschool",
    "Primary/Elementary",
    "Secondary/Middle/High School",
    TERTIARY_LABEL,
]

DCONF_LABELS = {"Preschool", "Primary/Elementary", "Secondary/Middle/High School"}


def dpkg_installed(package):
    try:
        r = subprocess.run(["dpkg", "-s", package],
                           capture_output=True, text=True)
        return r.returncode == 0
    except FileNotFoundError:
        return False


def apt_cache_description(package):
    try:
        r = subprocess.run(["apt-cache", "search", "^{}$".format(package)],
                           capture_output=True, text=True)
        for line in r.stdout.strip().splitlines():
            if line.startswith(package):
                parts = line.split(" - ", 1)
                if len(parts) == 2:
                    return parts[1].strip()
    except FileNotFoundError:
        pass
    return ""


def adm_members():
    try:
        return frozenset(grp.getgrnam("adm").gr_mem)
    except KeyError:
        return frozenset()


def list_non_admin_users():
    adm = adm_members()
    users = []
    for pw in pwd.getpwall():
        if pw.pw_uid >= 1000 and pw.pw_name != "nobody" and pw.pw_name not in adm:
            users.append(pw.pw_name)
    return sorted(users)


def get_current_default():
    for label, path in GSCHEMA_OVERRIDES.items():
        if path.exists():
            return label
    return TERTIARY_LABEL


def user_marker_path(username):
    pw = pwd.getpwnam(username)
    return Path(pw.pw_dir) / ".config" / "edubuntu" / "age-group"


def get_user_default(username):
    try:
        label = user_marker_path(username).read_text().strip()
        if label in DCONF_LABELS:
            return label
    except OSError:
        pass
    return TERTIARY_LABEL


def main():
    packages = []
    for pkg in METAPACKAGES:
        packages.append({
            "name": pkg,
            "description": apt_cache_description(pkg),
            "installed": dpkg_installed(pkg),
        })

    users = list_non_admin_users()
    user_data = []
    for u in users:
        user_data.append({
            "username": u,
            "age_group": get_user_default(u),
        })

    json.dump({
        "packages": packages,
        "global_default": get_current_default(),
        "setup_choices": SETUP_CHOICES,
        "users": user_data,
    }, sys.stdout)


if __name__ == "__main__":
    main()
