#!/usr/bin/python3
# blob:summary=Alarms, countdown timers and a stopwatch that ring through systemd user timers
# blob:args=[status|alarm add <HH:MM> [days] [label]|alarm remove|toggle <id>|timer start <duration> [label]|timer pause|resume|cancel|extend <id>|stopwatch start|pause|reset|lap|ring alarm|timer <id>|stop-ring|snooze]
# blob:group=utilities

from __future__ import annotations

import json
import os
import re
import secrets
import signal
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Any

STATE_FILE = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local" / "state"))) / "blob" / "timers.json"
RUNTIME_FILE = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "blob" / "timers-ringing.json"
SCRIPT = str(Path(__file__).resolve())
SOUND = "/usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga"
DAY_NAMES = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
SNOOZE_MINUTES = 9
RING_SECONDS = 300
EMPTY_STATE = {"alarms": [], "timers": [], "stopwatch": {"running": False, "startedAt": 0, "elapsedBefore": 0, "laps": []}}


def now_ms() -> int:
  return int(time.time() * 1000)


def load() -> dict[str, Any]:
  try:
    data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
  except (OSError, ValueError):
    data = {}
  state = json.loads(json.dumps(EMPTY_STATE))
  if isinstance(data, dict):
    state.update({key: value for key, value in data.items() if key in EMPTY_STATE})
  return state


def save(state: dict[str, Any]) -> None:
  STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
  temporary = STATE_FILE.with_suffix(".tmp")
  temporary.write_text(json.dumps(state) + "\n", encoding="utf-8")
  temporary.replace(STATE_FILE)


def systemctl(*arguments: str) -> None:
  subprocess.run(["systemctl", "--user", *arguments], capture_output=True)


def schedule(unit: str, timing: list[str], command: list[str]) -> bool:
  systemctl("stop", f"{unit}.timer", f"{unit}.service")
  systemctl("reset-failed", f"{unit}.timer", f"{unit}.service")
  result = subprocess.run(
    ["systemd-run", "--user", "--quiet", "--collect", f"--unit={unit}",
     "--timer-property=AccuracySec=1s", *timing, SCRIPT, *command],
    capture_output=True, text=True,
  )
  if result.returncode != 0:
    print(result.stderr.strip() or "Could not schedule the timer", file=sys.stderr)
  return result.returncode == 0


def unschedule(unit: str) -> None:
  systemctl("stop", f"{unit}.timer", f"{unit}.service")
  systemctl("reset-failed", f"{unit}.timer", f"{unit}.service")


def new_id() -> str:
  return secrets.token_hex(4)


def parse_duration(text: str) -> int:
  text = text.strip().lower()
  if re.fullmatch(r"\d+(:\d{1,2}){1,2}", text):
    seconds = 0
    for part in text.split(":"):
      seconds = seconds * 60 + int(part)
    return seconds
  total = 0
  matched = False
  for amount, unit in re.findall(r"(\d+(?:\.\d+)?)\s*([hms]?)", text):
    matched = True
    total += float(amount) * {"h": 3600, "m": 60, "s": 1, "": 60}[unit]
  return int(total) if matched else 0


def parse_days(text: str) -> list[int]:
  text = text.lower()
  if text in ("", "once"):
    return []
  if text in ("daily", "every", "all"):
    return list(range(7))
  if text == "weekdays":
    return list(range(5))
  if text == "weekends":
    return [5, 6]
  days = []
  for part in text.split(","):
    for index, name in enumerate(DAY_NAMES):
      if part.strip().startswith(name.lower()[:2]) and index not in days:
        days.append(index)
  return sorted(days)


def alarm_calendar(alarm: dict[str, Any]) -> str:
  days = ",".join(DAY_NAMES[index] for index in alarm["days"]) + " " if alarm["days"] else ""
  return f"{days}*-*-* {alarm['time']}:00"


def schedule_alarm(alarm: dict[str, Any]) -> None:
  unit = f"blob-alarm-{alarm['id']}"
  if alarm["enabled"]:
    schedule(unit, [f"--on-calendar={alarm_calendar(alarm)}"], ["ring", "alarm", alarm["id"]])
  else:
    unschedule(unit)


def find(items: list[dict[str, Any]], item_id: str) -> dict[str, Any]:
  for item in items:
    if item["id"] == item_id:
      return item
  print(f"No item with id {item_id}", file=sys.stderr)
  raise SystemExit(1)


def timer_remaining(timer: dict[str, Any]) -> int:
  if timer["state"] == "running":
    return max(0, int((timer["endsAt"] - now_ms()) / 1000))
  return int(timer.get("remaining", 0))


def alarm_command(state: dict[str, Any], arguments: list[str]) -> int:
  action = arguments[0] if arguments else ""
  if action == "add" and len(arguments) > 1 and re.fullmatch(r"([01]?\d|2[0-3]):[0-5]\d", arguments[1]):
    hours, minutes = arguments[1].split(":")
    alarm = {
      "id": new_id(),
      "time": f"{int(hours):02d}:{minutes}",
      "days": parse_days(arguments[2] if len(arguments) > 2 else ""),
      "label": " ".join(arguments[3:]) if len(arguments) > 3 else "",
      "enabled": True,
    }
    state["alarms"].append(alarm)
    state["alarms"].sort(key=lambda entry: entry["time"])
    schedule_alarm(alarm)
  elif action == "remove" and len(arguments) > 1:
    alarm = find(state["alarms"], arguments[1])
    alarm["enabled"] = False
    schedule_alarm(alarm)
    state["alarms"].remove(alarm)
  elif action == "toggle" and len(arguments) > 1:
    alarm = find(state["alarms"], arguments[1])
    alarm["enabled"] = not alarm["enabled"]
    schedule_alarm(alarm)
  else:
    print("Use: alarm add <HH:MM> [once|daily|weekdays|weekends|mon,wed] [label], alarm remove <id>, alarm toggle <id>", file=sys.stderr)
    return 2
  save(state)
  return 0


def start_timer_unit(timer: dict[str, Any]) -> None:
  schedule(f"blob-timer-{timer['id']}", [f"--on-active={timer_remaining(timer)}s"], ["ring", "timer", timer["id"]])


def timer_command(state: dict[str, Any], arguments: list[str]) -> int:
  action = arguments[0] if arguments else ""
  if action == "start" and len(arguments) > 1:
    seconds = parse_duration(arguments[1])
    if seconds <= 0:
      print("Give a duration like 5m, 1h30m or 10:00", file=sys.stderr)
      return 2
    timer = {
      "id": new_id(), "label": " ".join(arguments[2:]), "duration": seconds,
      "endsAt": now_ms() + seconds * 1000, "remaining": seconds, "state": "running",
    }
    state["timers"].append(timer)
    start_timer_unit(timer)
  elif action in ("pause", "resume", "cancel", "extend") and len(arguments) > 1:
    timer = find(state["timers"], arguments[1])
    if action == "pause" and timer["state"] == "running":
      timer["remaining"] = timer_remaining(timer)
      timer["state"] = "paused"
      unschedule(f"blob-timer-{timer['id']}")
    elif action == "resume" and timer["state"] == "paused":
      timer["endsAt"] = now_ms() + timer["remaining"] * 1000
      timer["state"] = "running"
      start_timer_unit(timer)
    elif action == "extend":
      if timer["state"] == "done":
        timer["remaining"] = 0
        timer["endsAt"] = now_ms()
        timer["state"] = "running"
      if timer["state"] == "running":
        timer["endsAt"] += 60000
        start_timer_unit(timer)
      else:
        timer["remaining"] += 60
      timer["duration"] += 60
    elif action == "cancel":
      unschedule(f"blob-timer-{timer['id']}")
      state["timers"].remove(timer)
  else:
    print("Use: timer start <duration> [label], timer pause|resume|cancel|extend <id>", file=sys.stderr)
    return 2
  save(state)
  return 0


def stopwatch_command(state: dict[str, Any], arguments: list[str]) -> int:
  watch = state["stopwatch"]
  action = arguments[0] if arguments else ""
  elapsed = watch["elapsedBefore"] + (now_ms() - watch["startedAt"] if watch["running"] else 0)
  if action == "start" and not watch["running"]:
    watch.update(running=True, startedAt=now_ms())
  elif action == "pause" and watch["running"]:
    watch.update(running=False, elapsedBefore=elapsed, startedAt=0)
  elif action == "reset":
    watch.update(running=False, elapsedBefore=0, startedAt=0, laps=[])
  elif action == "lap" and elapsed > 0:
    watch["laps"].append(elapsed)
  elif action not in ("start", "pause", "lap"):
    print("Use: stopwatch start|pause|reset|lap", file=sys.stderr)
    return 2
  save(state)
  return 0


def ring(kind: str, item_id: str) -> int:
  state = load()
  items = state["alarms"] if kind == "alarm" else state["timers"]
  item = next((entry for entry in items if entry["id"] == item_id), None)
  if item is None:
    return 0
  if kind == "alarm":
    title = "Alarm  " + item["time"]
    if not item["days"]:
      item["enabled"] = False
      unschedule(f"blob-alarm-{item_id}")
  else:
    item.update(state="done", remaining=0)
    minutes, seconds = divmod(item["duration"], 60)
    title = "Timer done  " + (f"{minutes}m {seconds}s" if seconds else f"{minutes}m")
  save(state)
  RUNTIME_FILE.parent.mkdir(parents=True, exist_ok=True)
  RUNTIME_FILE.write_text(json.dumps({"kind": kind, "id": item_id, "title": title, "label": item.get("label", ""), "pid": os.getpid()}), encoding="utf-8")
  stop = threading.Event()

  def play() -> None:
    deadline = time.time() + RING_SECONDS
    while not stop.is_set() and time.time() < deadline:
      subprocess.run(["pw-play", SOUND], capture_output=True)

  player = threading.Thread(target=play, daemon=True)
  player.start()
  signal.signal(signal.SIGTERM, lambda *_: stop.set() or sys.exit(0))
  actions = ["-A", "stop=Stop"] + (["-A", "snooze=Snooze"] if kind == "alarm" else ["-A", "extend=+1 min"])
  try:
    chosen = subprocess.run(
      ["notify-send", "-a", "Timers", "-u", "critical", *actions, title, item.get("label") or "Time is up"],
      capture_output=True, text=True, timeout=RING_SECONDS,
    ).stdout.strip()
  except subprocess.TimeoutExpired:
    chosen = ""
  stop.set()
  RUNTIME_FILE.unlink(missing_ok=True)
  if chosen == "snooze":
    snooze_alarm(item_id)
  elif chosen == "extend":
    timer_command(load(), ["extend", item_id])
  return 0


def snooze_alarm(item_id: str) -> None:
  schedule(f"blob-snooze-{item_id}", [f"--on-active={SNOOZE_MINUTES * 60}s"], ["ring", "alarm-snoozed", item_id])


def ringing() -> dict[str, Any] | None:
  try:
    data = json.loads(RUNTIME_FILE.read_text(encoding="utf-8"))
    os.kill(int(data["pid"]), 0)
    return data
  except (OSError, ValueError, KeyError, TypeError):
    return None


def stop_ring(snooze: bool) -> int:
  current = ringing()
  if current is None:
    return 0
  try:
    os.kill(int(current["pid"]), signal.SIGTERM)
  except OSError:
    pass
  RUNTIME_FILE.unlink(missing_ok=True)
  if snooze and current["kind"] == "alarm":
    snooze_alarm(current["id"])
  return 0


def next_alarm(state: dict[str, Any]) -> dict[str, Any] | None:
  current = time.localtime()
  minutes_now = current.tm_hour * 60 + current.tm_min
  best = None
  for alarm in state["alarms"]:
    if not alarm["enabled"]:
      continue
    hours, minutes = map(int, alarm["time"].split(":"))
    target = hours * 60 + minutes
    for offset in range(8):
      weekday = (current.tm_wday + offset) % 7
      if alarm["days"] and weekday not in alarm["days"]:
        continue
      if offset == 0 and target <= minutes_now:
        continue
      wait = offset * 1440 + target - minutes_now
      if best is None or wait < best["inMinutes"]:
        best = {"id": alarm["id"], "time": alarm["time"], "label": alarm["label"], "inMinutes": wait}
      break
  return best


def status() -> dict[str, Any]:
  state = load()
  for timer in state["timers"]:
    timer["remainingNow"] = timer_remaining(timer)
  return dict(state, now=now_ms(), nextAlarm=next_alarm(state), ringing=ringing())


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "status"
  rest = arguments[1:]
  if action == "status":
    print(json.dumps(status()))
    return 0
  if action == "alarm":
    return alarm_command(load(), rest)
  if action == "timer":
    return timer_command(load(), rest)
  if action == "stopwatch":
    return stopwatch_command(load(), rest)
  if action == "ring" and len(rest) == 2:
    return ring("alarm" if rest[0].startswith("alarm") else "timer", rest[1])
  if action == "stop-ring":
    return stop_ring(False)
  if action == "snooze":
    return stop_ring(True)
  print("blob-timers does not understand: " + " ".join(arguments), file=sys.stderr)
  return 2


if __name__ == "__main__":
  sys.exit(main(sys.argv[1:]))
