#!/usr/bin/env -S python3 -X utf8
# summary: Read or change Night light settings.
"""starchaser nightlight: night light (a warmer screen in the evening) for Settings > Displays and Quick settings.

    starchaser nightlight status                  the settings and what it's doing now, as JSON
    starchaser nightlight on | off | toggle       turn it on or off (prints the new status)
    starchaser nightlight warmth <0-100>          how warm: 0 is a little, 100 is the warmest (prints the status)
    starchaser nightlight schedule sun            from sunset to sunrise (estimated from your time zone)
    starchaser nightlight schedule custom <from> <to>   your own times, 24-hour HH:MM (21:00 07:00)
    starchaser nightlight schedule always         warm all the time while it's on
    starchaser nightlight preview                 show the warmth for 10 seconds, even when night light is off
    starchaser nightlight stop-preview            end the preview without changing your saved choices
    starchaser nightlight run                     internal: the background service that warms the screen

The choices live in ~/.config/starchaser/nightlight.json. A user service (starchaser-nightlight.service) keeps
the screen-warming tool running while the screen should be warm and stops it when it shouldn't; stopping it puts
the colors back. Turning night light on installs and starts that
service if it isn't set up yet.

Sunset and sunrise come from your time zone's main city (the coordinates in /usr/share/zoneinfo/zone1970.tab): no
location lookup and nothing sent anywhere. A time zone without coordinates uses 7:00 PM to 7:00 AM.
"""
import datetime as dt
import fcntl
import json
import math
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from pathlib import Path

CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
STATE = CONFIG / "starchaser/nightlight.json"
LOCK = CONFIG / "starchaser/.nightlight.lock"         # held from load() to save() by every command that changes STATE
RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}")
LIVE = RUNTIME / "starchaser-nightlight.json"          # what the service is doing now (written by `run`)
ERRS = RUNTIME / "starchaser-nightlight.err"           # hyprsunset's own messages (the last line explains a failure)
PREVIEW = RUNTIME / "starchaser-nightlight.preview"   # preview deadline; negative while waiting for the warmer (CLOCK_MONOTONIC)
PREVIEW_SECONDS = 10
UNIT = "starchaser-nightlight.service"
DEFAULTS = {"on": False, "warmth": 50, "schedule": "sun", "from": "21:00", "to": "07:00"}
SCHEDULES = ("sun", "custom", "always")
FALLBACK = ("19:00", "07:00")


def kelvin(warmth: int) -> int:
    """0 = a little warmer (5500 K), 100 = the warmest (2500 K); daylight is about 6500 K."""
    return int(round(5500 - 30 * max(0, min(100, warmth))))


BROKEN_KEPT = ""


def keep_broken() -> None:
    """A settings file that can't be read is kept beside the new one (nightlight.json.broken), so nothing is lost."""
    global BROKEN_KEPT
    dest = STATE.with_name(STATE.name + ".broken")
    try:
        dest.write_bytes(STATE.read_bytes())
    except OSError:
        return
    BROKEN_KEPT = dest.name


def load() -> dict:
    st = dict(DEFAULTS)
    try:
        raw = json.loads(STATE.read_text())
    except FileNotFoundError:
        raw = None
    except (OSError, ValueError, RecursionError):
        raw = None
    if isinstance(raw, dict):
        st.update({k: raw[k] for k in DEFAULTS if k in raw})
    else:
        if STATE.exists() and not BROKEN_KEPT:
            keep_broken()
            if BROKEN_KEPT:
                print(f"starchaser nightlight: the settings in nightlight.json couldn't be read and were kept as "
                      f"{BROKEN_KEPT}; the night light settings start from their defaults.", file=sys.stderr)
    st["on"] = st["on"] is True
    try:
        st["warmth"] = max(0, min(100, int(st["warmth"])))
    except (TypeError, ValueError):
        st["warmth"] = DEFAULTS["warmth"]
    if st["schedule"] not in SCHEDULES:
        st["schedule"] = DEFAULTS["schedule"]
    for k in ("from", "to"):
        if parse_hm(st[k]) is None:
            st[k] = DEFAULTS[k]
    return st


def locked():
    """The settings lock, held until the returned file is closed: two quick changes (warmth, then the schedule) each
    read, change and write the whole file, so without it the second could write back what the first replaced."""
    LOCK.parent.mkdir(parents=True, exist_ok=True)
    f = open(LOCK, "a")
    fcntl.flock(f, fcntl.LOCK_EX)
    return f


def save(st: dict) -> None:
    STATE.parent.mkdir(parents=True, exist_ok=True)
    tmp = STATE.with_suffix(".tmp")
    tmp.write_text(json.dumps({k: st[k] for k in DEFAULTS}, indent=2) + "\n")
    tmp.replace(STATE)


def parse_hm(s) -> "int | None":
    """'21:30' -> minutes after midnight, or None."""
    try:
        h, m = str(s).split(":")
        h, m = int(h), int(m)
    except ValueError:
        return None
    return h * 60 + m if 0 <= h < 24 and 0 <= m < 60 else None


def hm(minutes: float) -> str:
    minutes = int(round(minutes)) % (24 * 60)
    return f"{minutes // 60:02d}:{minutes % 60:02d}"


# ---- sunset and sunrise from the time zone
def zone_name() -> str:
    try:
        out = subprocess.run(["timedatectl", "show", "-p", "Timezone", "--value"], capture_output=True, text=True,
                             timeout=3).stdout.strip()
        if out:
            return out
    except (OSError, subprocess.SubprocessError):
        pass
    try:
        return os.readlink("/etc/localtime").split("zoneinfo/", 1)[1]
    except (OSError, IndexError):
        return ""


def _dms(s: str, deg_digits: int) -> float:
    sign = -1 if s[0] == "-" else 1
    d = s[1:]
    deg, mins = int(d[:deg_digits]), int(d[deg_digits:deg_digits + 2])
    secs = int(d[deg_digits + 2:deg_digits + 4] or 0)
    return sign * (deg + mins / 60 + secs / 3600)


def zone_coords(zone: str) -> "tuple | None":
    """(latitude, longitude) of the time zone's main city, from tzdata's own table."""
    for tab in ("/usr/share/zoneinfo/zone1970.tab", "/usr/share/zoneinfo/zone.tab"):
        try:
            lines = Path(tab).read_text().splitlines()
        except OSError:
            continue
        for line in lines:
            if line.startswith("#"):
                continue
            f = line.split("\t")
            if len(f) >= 3 and f[2] == zone:
                c = f[1]
                cut = max(c.rfind("+"), c.rfind("-"))
                lat, lon = c[:cut], c[cut:]
                try:
                    return _dms(lat, 2), _dms(lon, 3)
                except ValueError:
                    return None
    return None


def _sun_utc_hours(day: dt.date, lat: float, lon: float, rising: bool) -> "float | None | str":
    """Sunrise or sunset in UTC hours (the almanac method, zenith 90.833 degrees). 'up' / 'down' when the sun
    doesn't rise or set that day."""
    rad, deg = math.radians, math.degrees
    n = day.timetuple().tm_yday
    lng_hour = lon / 15
    t = n + ((6 if rising else 18) - lng_hour) / 24
    m = 0.9856 * t - 3.289
    L = (m + 1.916 * math.sin(rad(m)) + 0.020 * math.sin(rad(2 * m)) + 282.634) % 360
    ra = deg(math.atan(0.91764 * math.tan(rad(L)))) % 360
    ra = (ra + (math.floor(L / 90) * 90 - math.floor(ra / 90) * 90)) / 15
    sin_dec = 0.39782 * math.sin(rad(L))
    cos_dec = math.cos(math.asin(sin_dec))
    cos_h = (math.cos(rad(90.833)) - sin_dec * math.sin(rad(lat))) / (cos_dec * math.cos(rad(lat)))
    if cos_h > 1:
        return "down"             # the sun stays down all day
    if cos_h < -1:
        return "up"               # the sun stays up all day
    h = (360 - deg(math.acos(cos_h)) if rising else deg(math.acos(cos_h))) / 15
    return (h + ra - 0.06571 * t - 6.622 - lng_hour) % 24


def sun_window(day: dt.date) -> dict:
    """{'from': 'HH:MM' (sunset), 'to': 'HH:MM' (sunrise), 'estimated': how it was worked out}, in local time."""
    zone = zone_name()
    where = zone_coords(zone) if zone else None
    if not where:
        return {"from": FALLBACK[0], "to": FALLBACK[1], "how": "fixed"}
    lat, lon = where
    try:
        from zoneinfo import ZoneInfo
        tz = ZoneInfo(zone)
    except Exception:
        tz = None
    noon = dt.datetime.combine(day, dt.time(12), tzinfo=tz) if tz else dt.datetime.now().astimezone()
    offset = (noon.utcoffset() or dt.timedelta()).total_seconds() / 3600
    rise = _sun_utc_hours(day, lat, lon, True)
    sset = _sun_utc_hours(day, lat, lon, False)
    if "down" in (rise, sset):
        return {"from": "00:00", "to": "00:00", "how": "dark"}      # warm all day
    if "up" in (rise, sset):
        return {"from": "00:00", "to": "00:00", "how": "light"}     # never warm
    return {"from": hm((sset + offset) * 60), "to": hm((rise + offset) * 60), "how": "zone"}


def window(st: dict, day: dt.date) -> dict:
    if st["schedule"] == "custom":
        return {"from": st["from"], "to": st["to"], "how": "custom"}
    if st["schedule"] == "always":
        return {"from": "00:00", "to": "00:00", "how": "always"}
    return sun_window(day)


def previewing() -> bool:
    """A short look at the warmth is under way: it does not touch the saved schedule and ends by itself."""
    try:
        return time.monotonic() < abs(float(PREVIEW.read_text()))
    except (OSError, ValueError):
        return False


def temperature_ready(env: dict, k: int) -> bool:
    """A live process alone does not mean its socket or screen temperature is ready."""
    try:
        result = subprocess.run(["hyprctl", "hyprsunset", "temperature"], env=dict(os.environ, **env),
                                capture_output=True, text=True, timeout=1)
        return result.returncode == 0 and result.stdout.strip() == str(k)
    except (OSError, subprocess.SubprocessError):
        return False


def start_preview_clock() -> None:
    # Off and a new preview use the same lock, so a late readiness check cannot revive a canceled preview.
    with locked():
        try:
            deadline = float(PREVIEW.read_text())
            if deadline < 0 and time.monotonic() < -deadline:
                PREVIEW.write_text(str(time.monotonic() + PREVIEW_SECONDS))
        except (OSError, ValueError):
            pass


def warm_now(st: dict, now: "dt.datetime | None" = None) -> bool:
    if not st["on"]:
        return False
    now = now or dt.datetime.now()
    w = window(st, now.date())
    if w["how"] in ("always", "dark"):
        return True
    if w["how"] == "light":
        return False
    a, b, t = parse_hm(w["from"]), parse_hm(w["to"]), now.hour * 60 + now.minute
    if a == b:
        return False
    return a <= t < b if a < b else (t >= a or t < b)


# ---- the background service
def hypr_env() -> "dict | None":
    """WAYLAND_DISPLAY and HYPRLAND_INSTANCE_SIGNATURE of the running Hyprland, or None when there's none."""
    sig, wl = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"), os.environ.get("WAYLAND_DISPLAY")
    if sig and wl and (RUNTIME / "hypr" / sig).is_dir() and (RUNTIME / wl).exists():
        return {"HYPRLAND_INSTANCE_SIGNATURE": sig, "WAYLAND_DISPLAY": wl}
    try:
        out = subprocess.run(["hyprctl", "instances", "-j"], capture_output=True, text=True, timeout=3).stdout
        found = json.loads(out or "[]")
    except (OSError, ValueError, subprocess.SubprocessError):
        return None
    for i in sorted(found, key=lambda x: x.get("time", 0), reverse=True):
        sig, wl = i.get("instance"), i.get("wl_socket")
        if sig and wl and (RUNTIME / wl).exists():
            return {"HYPRLAND_INSTANCE_SIGNATURE": sig, "WAYLAND_DISPLAY": wl}
    return None


def write_live(d: dict) -> None:
    """What the service is doing now, with its pid (service_alive). Written only when it changes: the runtime folder is
    watched by the taskbar's file readers, and a write every 2 seconds woke each of them for nothing."""
    d = dict(d, pid=os.getpid())
    try:
        if json.loads(LIVE.read_text()) == d:
            return
    except (OSError, ValueError, RecursionError):
        pass
    try:
        tmp = LIVE.with_suffix(".tmp")
        tmp.write_text(json.dumps(d))
        tmp.replace(LIVE)
    except OSError:
        pass


def next_minute() -> float:
    """Seconds until the next whole minute: every schedule changes on one (HH:MM), so the service looks then."""
    return 60.05 - time.time() % 60


def run() -> None:
    child, child_k, started, fails, error, mtime = None, 0, 0.0, 0, "", None
    wake = threading.Event()
    signal.signal(signal.SIGUSR1, lambda *_: wake.set())
    # the warmer ending by itself is looked at at once, not at the next minute (other children, such as the
    # readiness question to hyprctl, wake nothing)
    signal.signal(signal.SIGCHLD, lambda *_: wake.set() if child and child.poll() is not None else None)
    signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))

    def stop():
        nonlocal child
        if child and child.poll() is None:
            child.terminate()
            try:
                child.wait(3)
            except subprocess.TimeoutExpired:
                child.kill()
        child = None

    try:
        while True:
            wake.clear()
            try:
                m = STATE.stat().st_mtime
            except OSError:
                m = None
            if m != mtime:                      # a new choice: try again even after a failure
                mtime, fails, error = m, 0, ""
            # hyprsunset installed after it was found missing: try again by itself instead of staying failed
            if fails >= 3 and error == "hyprsunset isn't installed" and shutil.which("hyprsunset"):
                fails, error = 0, ""
            st = load()
            want = warm_now(st) or previewing()
            k = kelvin(st["warmth"])
            env = hypr_env() if want else None
            if child and child.poll() is not None:          # it ended by itself
                try:
                    err = ERRS.read_text(errors="replace").strip().splitlines()
                except OSError:
                    err = []
                fails = fails + 1 if time.time() - started < 5 else 0
                error = err[-1] if err else "hyprsunset stopped"
                child = None
            if want and env and fails < 3:
                if child and child_k != k:
                    stop()
                if not child:
                    if not shutil.which("hyprsunset"):
                        error, fails = "hyprsunset isn't installed", 3
                    else:
                        with open(ERRS, "w") as errs:      # a file, not a pipe nobody reads (a full pipe would stall it)
                            child = subprocess.Popen(["hyprsunset", "-t", str(k)], env=dict(os.environ, **env),
                                                     stdout=subprocess.DEVNULL, stderr=errs)
                        child_k, started = k, time.time()
            elif not want or not env:      # off, or no desktop to warm (logging out): do not leave it running
                stop()
            running = bool(child and child.poll() is None and temperature_ready(env, child_k))
            if running:
                start_preview_clock()
            elif child and time.time() - started >= 5:
                stop()
                fails, error = 3, "The screen warmer did not become ready"
            write_live({"warm": running, "kelvin": child_k if running else 0,
                        "failed": fails >= 3, "error": error if fails >= 3 else ""})
            # Check readiness promptly during startup and a preview every second; otherwise look again at the next
            # minute, when a schedule can change (a new choice, a preview and the warmer ending wake it at once).
            wake.wait(0.1 if child and not running else 1 if previewing() else next_minute())
    finally:
        stop()


# ---- the commands
def service_alive() -> bool:
    """The service that wrote the live file is still running (its pid is this program's `run`)."""
    try:
        data = json.loads(LIVE.read_text())
        pid = data.get("pid") if isinstance(data, dict) else None
        if type(pid) is not int or pid <= 0:
            return False
        args = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")
        return any(os.path.basename(a) == os.fsencode(Path(__file__).name) for a in args) and b"run" in args
    except (OSError, ValueError, TypeError, RecursionError):
        return False


def ensure_service() -> None:
    """Start the service (setting it up first on a computer set up before night light existed)."""
    if service_alive():
        subprocess.run(["systemctl", "--user", "kill", "--kill-whom=main", "--signal=USR1", UNIT], capture_output=True)
        return
    unit = CONFIG / "systemd/user" / UNIT
    if not unit.exists():
        src = Path(__file__).resolve().parent.parent / "config/systemd/user" / UNIT
        if src.exists():
            unit.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(src, unit)
            subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
    subprocess.run(["systemctl", "--user", "enable", UNIT], capture_output=True)
    subprocess.run(["systemctl", "--user", "restart", UNIT], capture_output=True)


def status() -> dict:
    st = load()
    today = window(st, dt.date.today())
    sun = sun_window(dt.date.today())
    try:
        live = json.loads(LIVE.read_text()) if service_alive() else {}
    except (OSError, ValueError, RecursionError):
        live = {}
    if not isinstance(live, dict):
        live = {}
    return dict(st, kelvin=kelvin(st["warmth"]), installed=bool(shutil.which("hyprsunset")),
                service=service_alive(), shouldBeWarm=warm_now(st), previewing=previewing(), warm=bool(live.get("warm")),
                failed=bool(live.get("failed")), error=live.get("error", ""),
                # the Quick settings tile grays itself with "Not on this screen" when this is false
                supported=not live.get("failed"),
                start=today["from"], end=today["to"], how=today["how"],
                sunset=sun["from"], sunrise=sun["to"], sunHow=sun["how"], zone=zone_name())


def main(argv: list) -> None:
    cmd = argv[0] if argv else "status"
    if cmd == "run" and len(argv) == 1:
        return run()
    if cmd == "status" and len(argv) <= 1:
        print(json.dumps(status()))
        return
    if cmd == "preview" and len(argv) == 1:
        PREVIEW.parent.mkdir(parents=True, exist_ok=True)
        with locked():
            PREVIEW.write_text(str(-(time.monotonic() + PREVIEW_SECONDS)))
        ensure_service()
        print(json.dumps(status()))
        return
    if cmd == "stop-preview" and len(argv) == 1:
        with locked():
            PREVIEW.unlink(missing_ok=True)
        print(json.dumps(status()))
        return
    lock = locked()    # released by close() after save(), or when an error below exits
    st = load()
    if cmd in ("on", "off", "toggle") and len(argv) == 1:
        if cmd == "off" or (cmd == "toggle" and st["on"]):
            PREVIEW.unlink(missing_ok=True)
        st["on"] = (not st["on"]) if cmd == "toggle" else cmd == "on"
    elif cmd == "warmth" and len(argv) == 2:
        # a value out of range is refused, not quietly clamped (load() still clamps a saved file)
        try:
            n = int(argv[1])
        except ValueError:
            n = -1
        if not 0 <= n <= 100:
            print("starchaser nightlight: warmth is a number from 0 to 100", file=sys.stderr)
            sys.exit(2)
        st["warmth"] = n
    elif cmd == "schedule" and len(argv) >= 2 and argv[1] in SCHEDULES:
        if argv[1] == "custom":
            if len(argv) != 4 or parse_hm(argv[2]) is None or parse_hm(argv[3]) is None:
                print("starchaser nightlight: custom times are two 24-hour times, like 21:00 07:00", file=sys.stderr)
                sys.exit(2)
            if parse_hm(argv[2]) == parse_hm(argv[3]):
                print("starchaser nightlight: the start and end times have to be different", file=sys.stderr)
                sys.exit(2)
            st["from"], st["to"] = hm(parse_hm(argv[2])), hm(parse_hm(argv[3]))
        elif len(argv) != 2:
            print(f"starchaser nightlight: schedule {argv[1]} takes no times", file=sys.stderr)
            sys.exit(2)
        st["schedule"] = argv[1]
    else:
        # say what was wrong first, then the help
        known = ("run", "status", "on", "off", "toggle", "warmth", "schedule", "preview", "stop-preview")
        if cmd.startswith("-"):
            print(f"starchaser nightlight: unknown option {cmd!r}. Run 'starchaser nightlight --help' for more help.", file=sys.stderr)
        elif cmd not in known:
            print(f"starchaser nightlight: unknown command {cmd!r}. Run 'starchaser nightlight --help' for more help.", file=sys.stderr)
        elif cmd == "schedule" and len(argv) >= 2:
            print(f"starchaser nightlight: unknown schedule '{argv[1]}'. "
                  "Run 'starchaser nightlight --help' for more help.", file=sys.stderr)
        else:
            print(f"starchaser nightlight: wrong number of words after '{cmd}'. "
                  "Run 'starchaser nightlight --help' for more help.", file=sys.stderr)
        sys.exit(2)
    save(st)
    lock.close()
    if st["on"]:
        ensure_service()
    print(json.dumps(status()))


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]) or any(a in ("-h", "--help") for a in sys.argv[2:]):
        print(__doc__.strip())
        sys.exit(0)
    try:
        main(sys.argv[1:])
    except PermissionError as error:       # a settings folder it may not write: say so, not a traceback
        sys.exit(f"starchaser nightlight: couldn't save your settings ({error.strerror}). Check that you can write to ~/.config.")
