#!/usr/bin/python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Bind each Pocket DS touchscreen to its panel via kcminputrc.

Plasma 6 stores per-touchscreen output mapping as

    [Libinput][<vid>][<pid>][<device-name>]
    OutputUuid=<connector-uuid>

The connector UUID is generated by KWin on first session start
and persisted in ~/.config/kwinoutputconfig.json under
[].data[].uuid for each [].name=='outputs' entry. We read it from
there and patch kcminputrc so each touchscreen points at its
panel by name (DSI-1 = main / 7", DSI-2 = secondary / 4").

Idempotent: re-running on every Plasma session start is fine; the
file is only rewritten when the mapping is missing or stale.
"""
import json
import sys
from configparser import ConfigParser
from pathlib import Path

TOUCH_TO_PANEL = {
    (0,    0,   "generic ft5x06 (44)"):           "DSI-1",
    (1046, 967, "Goodix Capacitive TouchScreen"): "DSI-2",
}

KWIN_CONF  = Path.home() / ".config" / "kwinoutputconfig.json"
KCMINPUT   = Path.home() / ".config" / "kcminputrc"


def panel_uuids():
    """Return {connectorName: uuid} from kwinoutputconfig.json."""
    if not KWIN_CONF.exists():
        return {}
    try:
        sections = json.loads(KWIN_CONF.read_text())
    except (json.JSONDecodeError, OSError):
        return {}
    out = {}
    for section in sections:
        if section.get("name") != "outputs":
            continue
        for entry in section.get("data", []):
            name = entry.get("connectorName")
            uuid = entry.get("uuid")
            if name and uuid:
                out[name] = uuid
    return out


def main() -> int:
    panels = panel_uuids()
    if not panels:
        # KWin hasn't populated UUIDs yet; nothing to do.
        return 0

    desired = {}
    for (vid, pid, name), panel in TOUCH_TO_PANEL.items():
        uuid = panels.get(panel)
        if uuid:
            desired[f"Libinput][{vid}][{pid}][{name}"] = uuid

    if not desired:
        return 0

    cfg = ConfigParser(strict=False, interpolation=None,
                       delimiters=("=",))
    cfg.optionxform = str  # KConfig is case-sensitive
    if KCMINPUT.exists():
        cfg.read(KCMINPUT)

    changed = False
    for section, uuid in desired.items():
        if not cfg.has_section(section):
            cfg.add_section(section)
        if cfg.get(section, "OutputUuid", fallback=None) != uuid:
            cfg.set(section, "OutputUuid", uuid)
            changed = True

    if changed:
        KCMINPUT.parent.mkdir(parents=True, exist_ok=True)
        with KCMINPUT.open("w") as f:
            cfg.write(f, space_around_delimiters=False)

    return 0


if __name__ == "__main__":
    sys.exit(main())
