#!/usr/bin/env python3
"""Compose the classroom's kdeglobals, colours included.

The panel came up light on a machine that had never had a colour scheme
applied to it, and dark on one that had. That is the whole bug in one
sentence: `ColorScheme=EkklesiaDark` is a label. KConfig reads the actual
colours out of [Colors:*] groups in kdeglobals, and nothing was putting
them there except a technician running classroom-theme once, by hand, on
a machine that then looked right for reasons the package did not own.

So the package ships the expanded palette in its own kdeglobals, at the
bottom of the cascade, where a room with no user configuration at all
finds it. One source of truth stays EkklesiaDark.colors: this composes,
it does not duplicate.

classroom-theme still works. plasma-apply-colorscheme writes the chosen
palette into the user's own kdeglobals, which sits ahead of this file, and
classroom-desktop-reset keeps a user palette whose name is an Ekklesia one.

    tools/build-kdeglobals > somewhere/kdeglobals
"""

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
POLICY = ROOT / "config/plasma/xdg/kdeglobals"
SCHEME = ROOT / "config/plasma/colors/EkklesiaDark.colors"

# Name belongs to the scheme file, not to a session's configuration, and
# ColorScheme is already stated in the policy file above.
SKIP_IN_GENERAL = {"Name", "ColorScheme"}


def groups(text):
    """Yield (header, [lines]) for each group in a KConfig file."""
    header = None
    body = []

    for line in text.splitlines():
        if line.startswith("["):
            if header is not None:
                yield header, body
            header, body = line, []
        elif header is not None:
            body.append(line)

    if header is not None:
        yield header, body


def policy_with(extra_general):
    """The policy file, with the scheme's stray [General] keys folded in.

    Two [General] headers in one file is asking a parser a question it
    should not be asked, so the keys go into the group that is already
    there.
    """
    lines = POLICY.read_text().rstrip("\n").splitlines()
    out = []
    inside = False

    for line in lines:
        if line.startswith("["):
            if inside:
                out.extend(extra_general)
                inside = False

            inside = line == "[General]"

        out.append(line)

    if inside:
        out.extend(extra_general)

    return "\n".join(out)


def main():
    extra_general = []

    for header, body in groups(SCHEME.read_text()):
        if header != "[General]":
            continue

        extra_general = [
            line
            for line in body
            if line.strip()
            and not line.startswith("#")
            and line.split("=", 1)[0].strip() not in SKIP_IN_GENERAL
        ]

    out = [policy_with(extra_general), ""]

    out.append(
        "# ------------------------------------------------------------------\n"
        "# Generated by tools/build-kdeglobals from EkklesiaDark.colors.\n"
        "# Do not edit here: edit the scheme file and rebuild the package.\n"
        "#\n"
        "# These are the colours themselves. Without them a room with no user\n"
        "# configuration gets KDE's built-in light palette however the scheme\n"
        "# above is named.\n"
        "# ------------------------------------------------------------------"
    )

    for header, body in groups(SCHEME.read_text()):
        lines = [line for line in body if line.strip() and not line.startswith("#")]

        if header == "[General]":
            # Already folded into the policy file's own [General] above.
            continue

        if not lines:
            continue

        out.append("")
        out.append(header)
        out.extend(lines)

    sys.stdout.write("\n".join(out) + "\n")


if __name__ == "__main__":
    main()
