#!/usr/bin/python3
"""OgroOS activation notices for the signed-in user (a systemd user timer): 14, 7, 3 and 1 days
before the subscription ends (while the end has not moved), once a day in the grace period and
once a day when not activated. "Activate" opens Settings > System > Activation. Never blocks.

SPDX-FileCopyrightText: 2026 Dhaka Tek
SPDX-License-Identifier: LicenseRef-OgroOS-Proprietary
"""
import datetime as dt
import json
import os
import subprocess
import sys

sys.dont_write_bytecode = True  # nothing left behind in /usr/lib after a purge
sys.path.insert(0, "/usr/lib/ogroos-activation")
import ogroos_activation as A  # noqa: E402

STATE = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"),
                     "ogroos-activation", "notified.json")


def main():
    s = A.read_public_status()
    try:
        with open(STATE) as fh:
            done = json.load(fh)
    except (OSError, ValueError):
        done = {}
    today = dt.date.today().isoformat()
    title = body = key = None
    also_done = []
    if s.get("state") == "activated" and s.get("days_to_end") is not None:
        d = s["days_to_end"]
        for t in (1, 3, 7, 14):
            if d < t:
                key = "end:%s:%d" % (s.get("valid_until"), t)
                break
        if key and key not in done:
            title = "Your OgroOS subscription ends soon"
            body = ("The subscription for this PC ends on %s (in %d day%s). Ask your IT department to renew it; "
                    "nothing else changes." % (A._dmy(s.get("subscription_ends")), d + 1, "" if d == 0 else "s"))
            # the larger thresholds are passed too: one notice, not several at once
            also_done = ["end:%s:%d" % (s.get("valid_until"), t) for t in (1, 3, 7, 14) if d < t]
    elif s.get("state") == "grace":
        key = "grace:" + today
        title = "Activate OgroOS — %d day%s left" % (s["days_left"], "" if s["days_left"] == 1 else "s")
        body = s.get("message", "")
    elif s.get("state") == "not-activated":
        key = "not:" + today
        title = "Activate OgroOS"
        body = s.get("message", "")
    if not title or key in done:
        return 0
    done[key] = today
    for k in also_done:
        done[k] = today
    os.makedirs(os.path.dirname(STATE), exist_ok=True)
    with open(STATE, "w") as fh:
        json.dump({k: v for k, v in done.items() if v >= (dt.date.today() - dt.timedelta(days=400)).isoformat()}, fh)
    try:
        action = "activate=Details" if s.get("state") == "activated" else "activate=Activate"
        r = subprocess.run(["notify-send", "--app-name=OgroOS", "--icon=dialog-password", "--action=" + action,
                            "--wait", title, body], capture_output=True, text=True, timeout=1800)
    except (OSError, subprocess.TimeoutExpired):
        return 0
    if r.stdout.strip() == "activate":
        # a unit of its own: this service's processes end with it
        subprocess.run(["systemd-run", "--user", "--collect", "--quiet", "--unit=ogroos-activation-settings-%d" % os.getpid(),
                        "--", "systemsettings", "kcm_ogroos_activation"],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
    return 0


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